package eu.dnetlib.client.header;

import java.util.Date;

import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Form;
import com.github.gwtbootstrap.client.ui.Modal;
import com.github.gwtbootstrap.client.ui.ModalFooter;
import com.github.gwtbootstrap.client.ui.Form.SubmitCompleteHandler;
import com.github.gwtbootstrap.client.ui.constants.BackdropType;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

import eu.dnetlib.client.header.NewFeatureWidget.HideListener;
import eu.dnetlib.client.leftColumn.OptionsWidget;
import eu.dnetlib.client.rightColumn.DataBox;
import eu.dnetlib.client.rightColumn.PreviewBox;
import eu.dnetlib.shared.SchemaAnswer;
import eu.dnetlib.shared.ValuesOfFields;

public class LoadWidget implements IsWidget{

	private FlowPanel flowPanel = new FlowPanel();
	private SavingInfoServiceAsync savingInfo = GWT.create(SavingInfoService.class);
	private SchemaAnswer schemaFromServer;
	
	
	public interface HideListener{
		public void onEvent();
	}
	
	private HideListener hideListener;
	
	public void setHideListener(HideListener hideListener){
		this.hideListener = hideListener;
	}
	
	public LoadWidget(SchemaAnswer schemaFromServer) {
		
		this.schemaFromServer = schemaFromServer;
		designPanelNew(false);
	}
	
	private void designPanelNew(boolean refresh){
		
		final Modal LoadChartConfirmationPopup = new Modal();

        LoadChartConfirmationPopup.addStyleName("confirmationModal");
        LoadChartConfirmationPopup.setBackdrop(BackdropType.STATIC);
        
        final Form form = new Form();
	    form.setAction(Window.Location.getPath()+"FileUpload");
	  
	    form.setVisible(false);
	    form.setEncoding(FormPanel.ENCODING_MULTIPART);
	    form.setMethod(FormPanel.METHOD_POST);
	    
		final FileUpload fileUpload = new FileUpload();
		fileUpload.setName("uploadFileName");
		fileUpload.getElement().setAttribute("accept", ".xml");
		
		fileUpload.setVisible(false);
		
		form.add(fileUpload);
		form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
			
			@Override
			public void onSubmitComplete(
					com.github.gwtbootstrap.client.ui.Form.SubmitCompleteEvent event) {
					if(!event.getResults().equals("TypeFailure")){
						savingInfo.load("/var/lib/tomcat7/webapps/"+Window.Location.getPath()+event.getResults(), new AsyncCallback<ValuesOfFields>() {
							
							@Override
							public void onSuccess(ValuesOfFields result) {
								LoadChartConfirmationPopup.hide();
								ValuesOfFields.getInstance();
								ValuesOfFields.setInstance(result);
								RootPanel.get("optionsColumn").clear();
								new PreviewBox();
								new DataBox();
								new OptionsWidget(schemaFromServer, ValuesOfFields.getInstance().getOptionSelected(), true);
								
							}
							
							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Corrupted file!");
							}
						});
					}else{
						Window.alert("Type must be .xml");
					}
			}
		});
		
		fileUpload.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				form.submit();
			}
		});

        LoadChartConfirmationPopup.setTitle("Loading chart");

        HTML message = new HTML("All your current data will be lost, continue anyway?");
        LoadChartConfirmationPopup.add(message);
        Anchor saveAnchor = new Anchor();
        saveAnchor.setText("Click here to save your progress");
    	final Date tempDate = new Date();
		final DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("dd-MM-yyyy");
        LoadChartConfirmationPopup.add(saveAnchor);
        saveAnchor.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				savingInfo.save(ValuesOfFields.getInstance(), Window.Location.getPath()+""+dateTimeFormat.format(tempDate)+".xml", new AsyncCallback<Boolean>() {
					
					@Override
					public void onSuccess(Boolean result) {
						Window.Location.replace(URL.encode(Window.Location.getPath()+"/DownloadFile?filename="+Window.Location.getPath()+""+dateTimeFormat.format(tempDate)+".xml"));
					}
					
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Unexpected error!");
					}
				});
			}
		});

        FlowPanel actionButtons = new FlowPanel();
        actionButtons.addStyleName("confirmationModalButtons");

        ModalFooter modalFooter = new ModalFooter();
        modalFooter.add(actionButtons);
        LoadChartConfirmationPopup.add(modalFooter);

        Button no = new Button("Cancel");
        no.setType(ButtonType.DEFAULT);
        no.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                LoadChartConfirmationPopup.hide();
                LoadChartConfirmationPopup.removeFromParent();
            }
        });
        actionButtons.add(no);

        Button yes = new Button("Load file");
        yes.setType(ButtonType.SUCCESS);
        yes.add(form);
        yes.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
            	fileUpload.click();
            }
        });
        actionButtons.add(yes);
        
       
        LoadChartConfirmationPopup.show();
        
	}
	

	
	@Override
	public Widget asWidget() {
		return flowPanel;
	}


}
