package eu.dnetlib.client.adminpanel;

import com.github.gwtbootstrap.client.ui.*;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.AlternateSize;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.Label;
import eu.dnetlib.espas.gui.client.FormFieldSet;
import eu.dnetlib.espas.gui.shared.DataProvider;

import java.util.Date;
import java.util.List;

/**
 * Created by stefania on 10/9/15.
 */
public class ManualHarvestForm implements IsWidget {

    private FlowPanel manualHarvestFormPanel = new FlowPanel();

    private Alert manualHarvestErrorAlert = new Alert();
    private Alert manualHarvestSuccessAlert = new Alert();

    private Form manualHarvestForm = new Form();

    private ListBox dataProvidersListBox = new ListBox();
    private TextBox dateFrom = new TextBox();
    private TextBox dateTo = new TextBox();

    private ObjectTypesWidget objectTypesWidget = new ObjectTypesWidget();

    private FlowPanel actionButtons = new FlowPanel();
    private Button harvestNow = new Button("Harvest Now!");

    private HarvestInfoServiceAsync harvestInfoService = GWT.create(HarvestInfoService.class);

    private DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    private TimeZone tz = TimeZone.createTimeZone(0);

    public ManualHarvestForm(List<DataProvider> dataProviders) {

        manualHarvestErrorAlert.setType(AlertType.ERROR);
        manualHarvestErrorAlert.setVisible(false);
        manualHarvestErrorAlert.setClose(false);
        manualHarvestFormPanel.add(manualHarvestErrorAlert);

        manualHarvestSuccessAlert.setType(AlertType.SUCCESS);
        manualHarvestSuccessAlert.setVisible(false);
        manualHarvestSuccessAlert.setClose(false);
        manualHarvestFormPanel.add(manualHarvestSuccessAlert);

        manualHarvestFormPanel.add(manualHarvestForm);

        dataProvidersListBox.addItem("-- none selected --", "noneSelected");
        for(DataProvider dataProvider : dataProviders   )
            dataProvidersListBox.addItem(dataProvider.getName(), dataProvider.getNamespace());
        dataProvidersListBox.setAlternateSize(AlternateSize.XLARGE);
        manualHarvestForm.add(new FormFieldSet("Data Provider", dataProvidersListBox));

        Label dateFromExample = new Label("e.g. " + dtf.format(new Date()));
        dateFromExample.addStyleName("comment");
        dateFromExample.addStyleName("fontItalic");

        dateFrom.setAlternateSize(AlternateSize.XLARGE);
        dateFrom.addStyleName("inputWithComment");
        manualHarvestForm.add(new FormFieldSet("Date From", dateFrom, dateFromExample));

        Label dateToExample = new Label("e.g. " + dtf.format(new Date()));
        dateToExample.addStyleName("comment");
        dateToExample.addStyleName("fontItalic");

        dateTo.setAlternateSize(AlternateSize.XLARGE);
        dateTo.addStyleName("inputWithComment");
        manualHarvestForm.add(new FormFieldSet("Date To", dateTo, dateToExample));

        objectTypesWidget.addStyleName("manualHarvestObjectTypes");
        manualHarvestForm.add(new FormFieldSet("Types", objectTypesWidget.asWidget()));

        actionButtons.addStyleName("actionButtons");
        manualHarvestFormPanel.add(actionButtons);

        harvestNow.setType(ButtonType.INFO);
        harvestNow.addStyleName("harvestNow");
        harvestNow.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {

                manualHarvestErrorAlert.setVisible(false);
                manualHarvestSuccessAlert.setVisible(false);

                boolean isValidFrom = isValidDateFrom();
                boolean isValidTo = isValidDateTo();

                List<String> selectedTypes = objectTypesWidget.getSelectedTypes();

                if (isValidFrom && isValidTo && !selectedTypes.isEmpty() && !dataProvidersListBox.getValue().equals("noneSelected")) {

                    final HTML loadingWheel = new HTML("<div class=\"loader-big\"></div><div class=\"whiteFilm\"></div>");
                    manualHarvestFormPanel.addStyleName("loading-big");
                    manualHarvestFormPanel.add(loadingWheel);

                    harvestInfoService.harvest(selectedTypes, DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateFrom.getValue()),
                            DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateTo.getValue()),
                            "http://resources.espas-fp7.eu/provider/" + dataProvidersListBox.getValue(),
                            new AsyncCallback<Void>() {

                        @Override
                        public void onFailure(Throwable throwable) {

                            manualHarvestFormPanel.removeStyleName("loading-big");
                            manualHarvestFormPanel.remove(loadingWheel);

                            manualHarvestErrorAlert.setText("Failed to start the harvesting process");
                            manualHarvestErrorAlert.setVisible(true);
                        }

                        @Override
                        public void onSuccess(Void aVoid) {

                            manualHarvestFormPanel.removeStyleName("loading-big");
                            manualHarvestFormPanel.remove(loadingWheel);

                            manualHarvestSuccessAlert.setText("Harvesting process started successfully");
                            manualHarvestSuccessAlert.setVisible(true);
                        }
                    });
                } else {

                    if(dateFrom.getValue().isEmpty() || dateTo.getValue().isEmpty()
                            || selectedTypes.isEmpty() || dataProvidersListBox.getValue().equals("noneSelected")) {
                        manualHarvestErrorAlert.setText("All fields are required");
                        manualHarvestErrorAlert.setVisible(true);
                    } else {
                        if(!isValidFrom && !isValidTo) {
                            manualHarvestErrorAlert.setText("Date From and Date To are invalid");
                            manualHarvestErrorAlert.setVisible(true);
                        } else if(!isValidFrom && isValidTo) {
                            manualHarvestErrorAlert.setText("Date From is invalid");
                            manualHarvestErrorAlert.setVisible(true);
                        } else if(isValidFrom && !isValidTo) {
                            manualHarvestErrorAlert.setText("Date To is invalid");
                            manualHarvestErrorAlert.setVisible(true);
                        }
                    }
                }

            }
        });
        actionButtons.add(harvestNow);
    }

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

    private boolean isValidDateFrom() {

        try {
            DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateFrom.getValue());
        } catch (Exception exc) {
            return false;
        }

        return true;
    }

    private boolean isValidDateTo() {

        try {
            DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateTo.getValue());
        } catch (Exception exc) {
            return false;
        }

        return true;
    }
}
