package eu.dnetlib.uoaadmintoolslibrary.services;

import eu.dnetlib.uoaadmintoolslibrary.dao.DivHelpContentDAO;
import eu.dnetlib.uoaadmintoolslibrary.entities.*;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.DivHelpContentResponse;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.DivIdResponse;

import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class DivHelpContentService {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private DivHelpContentDAO divHelpContentDAO;

    @Autowired
    DivIdService divIdService;

    @Autowired
    private PortalService portalService;

    public List<DivHelpContentResponse> getDivHelpContents(String pid, String page_route, String divIdId, String active) {

        Portal _portal = portalService.getPortal(pid);
        String portalId = null;
        if(_portal != null) {
            portalId = _portal.getId();
        }

//        DivId divId = divIdService.getDivIdByName(divId);
//        String divIdId = null;
//        if(divId != null) {
//            divIdId = divId.getId();
//        }

        List<DivHelpContentResponse> divHelpContentResponses = new ArrayList<>();

        List<DivHelpContent> divHelpContents = null;
        if(pid != null && divIdId != null && active != null) {
            divHelpContents = divHelpContentDAO.findByPortalAndDivIdAndIsActive(portalId, divIdId, Boolean.parseBoolean(active));
        } else if(pid != null && divIdId != null) {
            divHelpContents = divHelpContentDAO.findByPortalAndDivId(portalId, divIdId);
        } else if(pid != null && active != null) {
            divHelpContents = divHelpContentDAO.findByPortalAndIsActive(portalId, Boolean.parseBoolean(active));
        } else if(divIdId != null && active != null) {
            divHelpContents = divHelpContentDAO.findByDivIdAndIsActive(divIdId, Boolean.parseBoolean(active));
        } else if(pid != null) {
            divHelpContents = divHelpContentDAO.findByPortal(portalId);
        } else if(divIdId != null) {
            divHelpContents = divHelpContentDAO.findByDivId(divIdId);
        } else if(active != null){
            divHelpContents = divHelpContentDAO.findByIsActive(Boolean.parseBoolean(active));
        } else {
            divHelpContents = divHelpContentDAO.findAll();
        }

        for (DivHelpContent divHelpContent : divHelpContents) {
            DivIdResponse divIdResponse = null;
            DivId divId;
            if(divIdId == null) {
                divId = divIdService.getDivId(divHelpContent.getDivId());
            } else {
                divId = divIdService.getDivId(divIdId);
            }
            divIdResponse = divIdService.divIdResponseFromDivId(divId);

            if(pid == null) {
                _portal = portalService.getPortalById(divHelpContent.getPortal());
            }

            for(Page p : divIdResponse.getPages()) {
                if (page_route == null || p.getRoute().equals(page_route)) {
                    DivHelpContentResponse divHelpContentResponse = new DivHelpContentResponse(divHelpContent);
                    divHelpContentResponse.setDivId(divIdResponse);
                    divHelpContentResponse.setPortal(_portal);
                    divHelpContentResponses.add(divHelpContentResponse);
                    break;
                }
            }
        }

        return divHelpContentResponses;
    }


    public List<DivHelpContent> getDivHelpContentsBasic(String pid, String portalType, String pageId) {
        List<DivHelpContent> divHelpContents = null;

        Portal _portal = null;
        String portalId = null;
        if(pid != null) {
            _portal = portalService.getPortal(pid);
            portalService.checkPortalInfo(pid, portalType, _portal, pid, "pid");
            if(_portal != null) {
                portalId = _portal.getId();
            }
        }

        if(pid != null) {
            divHelpContents = divHelpContentDAO.findByPortal(portalId);
        } else {
            divHelpContents = divHelpContentDAO.findAll();
        }

        if(pageId != null) {
            Iterator<DivHelpContent> divHelpContentsIterator = divHelpContents.iterator();
            while (divHelpContentsIterator.hasNext()) {
                DivHelpContent divHelpContent = divHelpContentsIterator.next();

                String divIdId = divHelpContent.getDivId();
                DivId divId = divIdService.getDivId(divIdId);

                Boolean remove = true;
                for (String pageIdInDivId : divId.getPages()) {
                    if (pageId.equals(pageIdInDivId)) {
                        remove = false;
                        break;
                    }
                }
                if(remove) {
                    divHelpContentsIterator.remove();
                }
            }
        }

        return divHelpContents;
    }

    public DivHelpContent getDivHelpContent(String id) {
        return divHelpContentDAO.findById(id);
    }

    public DivHelpContent insertOrUpdateDivHelpContent(DivHelpContent divHelpContent) {
        return divHelpContentDAO.save(divHelpContent);
    }

    public void deleteDivHelpContent(String id) {
        divHelpContentDAO.delete(id);
    }

    public Boolean deleteDivHelpContents(List<String> divHelpContents, String pid, PortalType portalType) throws Exception {
        Portal portal = portalService.getPortal(pid);
        portalService.checkPortalInfo(pid, portalType.name(), portal, pid, "pid");

        for (String id: divHelpContents) {
            DivHelpContent divHelpContent = getDivHelpContent(id);
            if(divHelpContent == null) {
                throw new ContentNotFoundException("Div help content with id: " + id + " not found");
            }
            if(!divHelpContent.getPortal().equals(portal.getId())) {
                throw new MismatchingContentException("["+portalType+ " - "+ pid+"] Conflicting div help content: portal id: "+divHelpContent.getPortal());
            }

            divHelpContentDAO.delete(id);
        }
        return true;
    }

    public List<String> toggleDivHelpContent(List<String> divHelpContents, String status, String pid, PortalType portalType) throws Exception {
        Portal portal = portalService.getPortal(pid);
        portalService.checkPortalInfo(pid, portalType.name(), portal, pid, "pid");

        for (String id: divHelpContents) {
            log.debug("Id of divHelpContent: "+id);
            DivHelpContent divHelpContent = getDivHelpContent(id);
            if(divHelpContent == null) {
                throw new ContentNotFoundException("Div help content with id: " + id + " not found");
            }
            if(!divHelpContent.getPortal().equals(portal.getId())) {
                throw new MismatchingContentException("["+portalType+ " - "+ pid+"] Conflicting div help content: portal id: "+divHelpContent.getPortal());
            }

            divHelpContent.setIsActive(Boolean.parseBoolean(status));
            divHelpContentDAO.save(divHelpContent);
        }
        return divHelpContents;
    }

    public void addDivHelpContentsInPortal(String portalId, String portalType) {
        //String organizations_class_content = "<div> <p>Here you can write more details about the organizations related to your portal.</p> </div>";
        String link_context_form_content = "<div> <div><span class=\"uk-text-bold\"><span uk-icon=\"icon: info\">&nbsp;</span> Information:</span> Select a research portal and/or a category and search for a portal concept, or browse to the portal tree through the categories</div> </div>";
        String link_project_form_content = "<div> <div><span class=\"uk-text-bold\"><span uk-icon=\"icon: info\">&nbsp;</span> Information:</span> Search for projects using project name or grant id. Limit results filtering by funder.</div> </div>";
        String link_result_form_content = "<div> <div><span class=\"uk-text-bold\"><span uk-icon=\"icon: info\">&nbsp;</span> Information:</span></div> Search for research results in OpenAIRE information space, Datacite, CrossRef or ORCID. <div class=\"uk-text-small\">Use keywords, DOI (more than one - space separated), author&#39;s ORCID</div> </div>";
        String link_result_bulk_content = "<div> <div><span class=\"uk-text-bold\"><span uk-icon=\"icon: info\">&nbsp;</span> Information:</span> Upload a csv file containing a list of DOIs. For each DOI found in the file, metadata will be fetched from CrossRef or Datacite and will be added to your selected research results.</div> <div class=\"uk-margin-top uk-text-small\"><span class=\"uk-text-bold\">CSV format:</span> <ul class=\"uk-list\"> <li>The format of CSV file should be &quot;DOI&quot;,&quot;ACCESS_MODE&quot;,&quot;DATE&quot;.</li> <li>The value &quot;DOI&quot; is required</li> <li>Access mode column should have values: &quot;OPEN&quot;,&quot;CLOSED&quot; or &quot;EMBARGO&quot;.</li> <li>Date column valid format is YYYY-MM-DD and is required when access mode has value EMBARGO.</li> <li>In case access mode is not available default value is &quot;OPEN&quot;.</li> </ul> </div> </div>";
        String link_metadata_content = "<div> <div><span class=\"uk-text-bold\"><span uk-icon=\"icon: info\">&nbsp;</span> Information:</span> Manage access mode &amp; type of selected research results. For OpenAIRE this functionality isn&#39;t available.</div> </div>";

        String portal_footer_content = "<p class=\"uk-margin-remove-bottom\"><span style=\"font-size:12px\">OpenAIRE has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreements No. 777541 and 101017452</span></p>";
        String monitor_dashboard_footer_content = "<p class=\"uk-margin-remove-bottom\"><span style=\"font-size:12px\">This OpenAIRE MONITOR dashboard is part of a project that has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreements No. 777541 and 101017452</span></p>";
        String community_footer_content = "<p class=\"uk-margin-remove-bottom\"><span style=\"font-size:12px\">This OpenAIRE gateway is part of a project that has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreements No. 777541, 731011 and 101017452</span></p>";

        List<DivId> divIds = divIdService.getDivIdsByPortalType(portalType);

        for( DivId div : divIds ) {
            if (div != null) {
//                    (div.getOpenaire() && pid.equals("openaire")) ||
//                            (div.getConnect() && pid.equals("connect")) ||
//                            (div.getCommunities() && !pid.equals("openaire") && !pid.equals("connect"))
//            )) {
                /*
                if (div.getName().equals("organizations")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, organizations_class_content, false));
                } else
                */
                if (div.getName().equals("link-context-form")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, link_context_form_content, false));
                } else if (div.getName().equals("link-project-form")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, link_project_form_content, false));
                } else if (div.getName().equals("link-result-form")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, link_result_form_content, false));
                } else if (div.getName().equals("link-result-bulk")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, link_result_bulk_content, false));
                } else if (div.getName().equals("link-metadata")) {
                    this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, link_metadata_content, false));
                } else if (div.getName().equals("footer")) {
                    if(portalType.equals("community")) {
                        this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, community_footer_content, true));
                    } else if(portalType.equals("funder") || portalType.equals("ri") || portalType.equals("project") || portalType.equals("organization")) {
                        this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, monitor_dashboard_footer_content, true));
                    } else {
                        this.insertOrUpdateDivHelpContent(new DivHelpContent(div.getId(), portalId, portal_footer_content, true));
                    }
                }
            }
        }
    }
}
