package eu.dnetlib.client.user;

import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Form;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.AlternateSize;
import com.github.gwtbootstrap.client.ui.constants.FormType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import eu.dnetlib.client.*;
import eu.dnetlib.client.widgets.AutoCompleteWidget;
import eu.dnetlib.client.widgets.FormFieldSet;
import eu.dnetlib.goldoa.domain.Affiliation;
import eu.dnetlib.goldoa.domain.Organization;
import eu.dnetlib.goldoa.domain.Vocabulary;
import eu.dnetlib.shared.EligiblePresentAndFutureProjects;

/**
 * Created by stefania on 4/6/15.
 */
public class MyEligibleProjectsWidget implements IsWidget {

    private FlowPanel eligibleProjectsPanel = new FlowPanel();

    private FlowPanel selectAffiliationPanel = new FlowPanel();
    private HTML institutionsFormLabel = new HTML("<legend>Eligible projects by organisation</legend>");
    private Form institutionsForm = new Form();

    private ListBox institutions = new ListBox();

    private AutoCompleteWidget organizationAutoComplete = new AutoCompleteWidget("organisation", "Search...");
    private Label commentLabel = new Label();

    private Alert errorLabel = new Alert();

    private FlowPanel eligibleProjectListPanel = new FlowPanel();

    private DataServiceAsync dataService = GWT.create(DataService.class);
    private GoldOAConstants goldOAConstants = GWT.create(GoldOAConstants.class);

    public MyEligibleProjectsWidget() {

        eligibleProjectsPanel.addStyleName("eligibleProjectsPanel");

        institutionsForm.setType(FormType.HORIZONTAL);

        if(Utils.currentUserHasRoleApproved("moderator") || Utils.currentUserHasRoleApproved("administrator")
                || Utils.currentUserHasRoleApproved("accounting")) {


            AutoCompleteWidget.AutoCompleteListener organizationAutoCompleteListener = new AutoCompleteWidget.AutoCompleteListener() {
                @Override
                public void valueSelected(Vocabulary vocabulary) {

                    getEligibleProjects(vocabulary.getId());
                }
            };
            organizationAutoComplete.setAutoCompleteListener(organizationAutoCompleteListener);

            commentLabel.setText("Search using the name as it appears in CORDA");
            commentLabel.addStyleName("comment");
            commentLabel.addStyleName("fontItalic");

            institutionsForm.add(new FormFieldSet("Organization", organizationAutoComplete.asWidget(), commentLabel));

        } else if(Utils.currentUserHasRoleApproved("library_staff") || Utils.currentUserHasRoleApproved("researcher")
                || Utils.currentUserHasRoleApproved("project_coordinator")) {

            if(GoldOAPortal.currentUser.getAffiliations().size()>1) {

                institutions.addItem("None selected", "none");
                for (Affiliation affiliation : GoldOAPortal.currentUser.getAffiliations()) {
                    Organization organization = affiliation.getOrganization();
                    if (organization != null)
                        institutions.addItem(organization.getName(), organization.getId());
                }
                institutions.setAlternateSize(AlternateSize.XXLARGE);
                institutions.setName("institution");
                institutions.addChangeHandler(new ChangeHandler() {

                    @Override
                    public void onChange(ChangeEvent changeEvent) {

                        if (!institutions.getSelectedValue().equals("none"))
                            getEligibleProjects(institutions.getSelectedValue());
                    }
                });
                institutionsForm.add(new FormFieldSet("Organization", institutions));

            } else {

                eligibleProjectListPanel.addStyleName("eligibleProjectListPanel");
                if(!GoldOAPortal.currentUser.getAffiliations().isEmpty() && GoldOAPortal.currentUser.getAffiliations().get(0)!=null
                        && GoldOAPortal.currentUser.getAffiliations().get(0).getOrganization()!=null)
                    getEligibleProjects(GoldOAPortal.currentUser.getAffiliations().get(0).getOrganization().getId());
            }
        }

        selectAffiliationPanel.add(institutionsFormLabel);
        selectAffiliationPanel.add(institutionsForm);

        errorLabel.addStyleName("alertLabel");
        errorLabel.setType(AlertType.ERROR);
        errorLabel.setVisible(false);
        errorLabel.setClose(false);

        if( (Utils.currentUserHasRoleApproved("library_staff") || Utils.currentUserHasRoleApproved("researcher")
                || Utils.currentUserHasRoleApproved("project_coordinator")) && GoldOAPortal.currentUser.getAffiliations().size()>1)
            eligibleProjectsPanel.add(selectAffiliationPanel);
        eligibleProjectsPanel.add(errorLabel);
        eligibleProjectsPanel.add(eligibleProjectListPanel);
    }

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

    private void getEligibleProjects(String organizationId) {

        errorLabel.setVisible(false);

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

        dataService.getEligibleProjectsForOrganization(organizationId,
                new AsyncCallback<EligiblePresentAndFutureProjects>() {

                    @Override
                    public void onFailure(Throwable throwable) {

                        eligibleProjectListPanel.clear();
                        eligibleProjectListPanel.removeStyleName("loading");

                        errorLabel.setText(goldOAConstants.errorGettingEligibleProjectsByOrganization());
                        errorLabel.setVisible(true);
                    }

                    @Override
                    public void onSuccess(EligiblePresentAndFutureProjects eligiblePresentAndFutureProjects) {

                        eligibleProjectListPanel.clear();
                        eligibleProjectListPanel.removeStyleName("loading");

                        if(eligiblePresentAndFutureProjects!=null) {
                            EligibleProjectsInfoWidget eligibleProjectsInfoWidget = new EligibleProjectsInfoWidget(eligiblePresentAndFutureProjects);
                            eligibleProjectListPanel.add(eligibleProjectsInfoWidget.asWidget());
                        }
                    }
                });
    }
}
