package eu.dnetlib.openaire.community;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.escape.Escaper;
import com.google.common.xml.XmlEscapers;

import eu.dnetlib.openaire.exporter.model.community.CommunityContentprovider;
import eu.dnetlib.openaire.exporter.model.community.CommunityDetails;
import eu.dnetlib.openaire.exporter.model.community.CommunityOrganization;
import eu.dnetlib.openaire.exporter.model.community.CommunityProject;
import eu.dnetlib.openaire.exporter.model.community.CommunityStatus;
import eu.dnetlib.openaire.exporter.model.community.CommunitySummary;
import eu.dnetlib.openaire.exporter.model.community.CommunityZenodoCommunity;
import eu.dnetlib.openaire.exporter.model.community.selectioncriteria.SelectionCriteria;
import eu.dnetlib.openaire.exporter.model.context.Concept;
import eu.dnetlib.openaire.exporter.model.context.Context;
import eu.dnetlib.openaire.exporter.model.context.Param;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import static eu.dnetlib.openaire.common.Utils.escape;
import static eu.dnetlib.openaire.community.CommunityConstants.*;

public class CommunityMappingUtils {

	private final static String pattern = "yyyy-MM-dd'T'hh:mm:ss";

	private static final Log log = LogFactory.getLog(CommunityMappingUtils.class);

	public static CommunitySummary asCommunitySummary(final Context c) {
		final CommunitySummary summary = new CommunitySummary();

		summary.setId(c.getId());
		summary.setShortName(c.getLabel());
		summary.setLastUpdateDate(c.getLastUpdateDate());
		summary.setCreationDate(c.getCreationDate());
		summary.setQueryId(c.getId() + PIPE_SEPARATOR + c.getLabel());
		summary.setType(c.getType());

		final Map<String, List<Param>> params = c.getParams();
		if (params.containsKey(CSUMMARY_DESCRIPTION)) {
			summary.setDescription(asCsv(params.get(CSUMMARY_DESCRIPTION)));
		}
		if (params.containsKey(CSUMMARY_LOGOURL)) {
			summary.setLogoUrl(asCsv(params.get(CSUMMARY_LOGOURL)));
		}
		if (params.containsKey(CSUMMARY_STATUS)) {
			summary.setStatus(CommunityStatus.valueOf(firstValue(params, CSUMMARY_STATUS)));
		}
		if (params.containsKey(CSUMMARY_NAME)) {
			summary.setName(asCsv(params.get(CSUMMARY_NAME)));
		}
		if (params.containsKey(CSUMMARY_ZENODOC)) {
			summary.setZenodoCommunity(asCsv(params.get(CSUMMARY_ZENODOC)));
		}

		return summary;
	}

	public static CommunityDetails asCommunityProfile(final Context c)  {

		final CommunityDetails p = new CommunityDetails(asCommunitySummary(c));
		p.setLastUpdateDate(c.getLastUpdateDate());
		final Map<String, List<Param>> params = c.getParams();
		if (params.containsKey(CPROFILE_SUBJECT)) {
			p.setSubjects(splitValues(asValues(params.get(CPROFILE_SUBJECT)), CSV_DELIMITER));
		}
		if (params.containsKey(CPROFILE_FOS)) {
			p.setFos(splitValues(asValues(params.get(CPROFILE_FOS)), CSV_DELIMITER));
		}
		if (params.containsKey(CPROFILE_SDG)) {
			p.setSdg(splitValues(asValues(params.get(CPROFILE_SDG)), CSV_DELIMITER));
		}
		if (params.containsKey(CPROFILE_ADVANCED_CONSTRAINT)) {
			//In the map the string is the serialization of the json representing the selection criteria so it is a valid json
			p.setAdvancedConstraints(SelectionCriteria.fromJson(asCsv(params.get(CPROFILE_ADVANCED_CONSTRAINT))));

		}
		if (params.containsKey(CPROFILE_CREATIONDATE)){
			try {
				p.setCreationDate(org.apache.commons.lang3.time.DateUtils.parseDate(asCsv(params.get(CPROFILE_CREATIONDATE)), pattern));
			}catch(ParseException e) {
				log.debug("Exception on date format: " + e.getMessage());
			}
		}

		return p;
	}

	public static CommunityProject asCommunityProject(final String communityId, final Concept c) {

		final Map<String, List<Param>> p = c.getParams();
		final CommunityProject project = new CommunityProject();
		project.setCommunityId(communityId);
		project.setId(StringUtils.substringAfterLast(c.getId(), ID_SEPARATOR));
		project.setOpenaireId(firstValue(p, OPENAIRE_ID));
		project.setFunder(firstValue(p, CPROJECT_FUNDER));
		project.setGrantId(firstValue(p, CPROJECT_NUMBER));
		project.setName(firstValue(p, CPROJECT_FULLNAME));
		project.setAcronym(firstValue(p, CPROJECT_ACRONYM));

		return project;
	}

	public static CommunityContentprovider asCommunityDataprovider(final String communityId, final Concept c) {

		final Map<String, List<Param>> p = c.getParams();
		final CommunityContentprovider d = new CommunityContentprovider();
		d.setCommunityId(communityId);
		d.setId(StringUtils.substringAfterLast(c.getId(), ID_SEPARATOR));
		d.setOpenaireId(firstValue(p, OPENAIRE_ID));
		d.setName(firstValue(p, CCONTENTPROVIDER_NAME));
		d.setOfficialname(firstValue(p, CCONTENTPROVIDER_OFFICIALNAME));
		d.setSelectioncriteria(SelectionCriteria.fromJson(firstValue(p, CCONTENTPROVIDER_SELCRITERIA)));
		return d;
	}

	public static CommunityZenodoCommunity asCommunityZenodoCommunity(final String communityId, final Concept c){
		final CommunityZenodoCommunity z = new CommunityZenodoCommunity();
		final Map<String, List<Param>> p = c.getParams();
		z.setCommunityId(communityId);
		z.setId(StringUtils.substringAfterLast(c.getId(), ID_SEPARATOR));
		z.setZenodoid(firstValue(p,CZENODOCOMMUNITY_ID));
		//z.setName(c.getLabel());
		return z;
	}


	public static CommunityOrganization asCommunityOrganization(String id, Concept c) {
		final Map<String, List<Param>> p = c.getParams();
		final CommunityOrganization o = new CommunityOrganization();
		o.setCommunityId(id);
		o.setId(StringUtils.substringAfterLast(c.getId(), ID_SEPARATOR));
		o.setName(firstValue(p,CORGANIZATION_NAME));
		o.setLogo_url(getDecodedUrl(firstValue(p,CORGANIZATION_LOGOURL)));
		o.setWebsite_url(getDecodedUrl(firstValue(p,CORGANIZATION_WEBSITEURL)));

		return o;
	}

	private static String getDecodedUrl(final String encoded_url){
		if(encoded_url == null){
			return encoded_url;
		}
		return new String(Base64.getDecoder().decode(encoded_url));
	}


	private static List<String> splitValues(final Stream<String> stream, final String separator) {
		return stream.map(s -> s.split(separator))
				.map(Arrays::asList)
				.flatMap(List::stream)
				.filter(StringUtils::isNotBlank)
				.map(StringUtils::trim)
				.collect(Collectors.toList());
	}

	private static String firstValue(final Map<String, List<Param>> p, final String paramName) {
		return asValues(p.get(paramName)).findFirst().orElse(null);
	}

	private static String asCsv(final List<Param> params) {
		return asValues(params)
				.collect(Collectors.joining(CSV_DELIMITER));
	}

	private static Stream<String> asValues(final List<Param> params) {
		return params == null ? Stream.empty() : params.stream()
				.map(Param::getValue)
				.map(StringUtils::trim)
				.distinct();
	}

	public static String asProjectXML(final String contextId, final CommunityProject project) {
		final Escaper esc = XmlEscapers.xmlAttributeEscaper();
		final StringBuilder sb = new StringBuilder();
		sb.append(
				String.format(
						"<concept claim='false' id='%s%s%s%s' label='%s'>\n",
						escape(esc, contextId), PROJECTS_ID_SUFFIX, ID_SEPARATOR, escape(esc, String.valueOf(project.getId())), escape(esc, project.getAcronym())));
		sb.append(paramXML(CPROJECT_FULLNAME, project.getName()));
		sb.append(paramXML(CPROJECT_ACRONYM, project.getAcronym()));
		sb.append(paramXML(CPROJECT_NUMBER, project.getGrantId()));
		sb.append(paramXML(CPROJECT_FUNDER, project.getFunder()));
		sb.append(paramXML(OPENAIRE_ID, project.getOpenaireId()));
		sb.append("</concept>\n");
		return sb.toString();
	}

	public static String asContentProviderXML(final String contextId, final CommunityContentprovider ccp) {
		log.info("creating the XML for the content provider");
		final Escaper esc = XmlEscapers.xmlAttributeEscaper();
		final StringBuilder sb = new StringBuilder();
		sb.append(
				String.format(
						"<concept claim='false' id='%s%s%s%s' label='%s'>\n",
						escape(esc, contextId), CONTENTPROVIDERS_ID_SUFFIX, ID_SEPARATOR, escape(esc, String.valueOf(ccp.getId())), escape(esc, ccp.getName())));
		sb.append(paramXML(OPENAIRE_ID, ccp.getOpenaireId()));
		sb.append(paramXML(CCONTENTPROVIDER_NAME, ccp.getName()));
		sb.append(paramXML(CCONTENTPROVIDER_OFFICIALNAME, ccp.getOfficialname()));
		sb.append(paramXML(CCONTENTPROVIDER_ENABLED,CCONTENTPROVIDERENABLED_DEFAULT));
		sb.append(paramXMLNoEscape(CCONTENTPROVIDER_SELCRITERIA, ccp.toXML()));
		sb.append("</concept>\n");
		log.info(sb.toString());
		return sb.toString();
	}

	public static String asZenodoCommunityXML(final String contextId, final CommunityZenodoCommunity zc) {
		final Escaper esc = XmlEscapers.xmlAttributeEscaper();
		final StringBuilder sb = new StringBuilder();
		sb.append(
				String.format(
						"<concept claim='false' id='%s%s%s%s' label='%s'>\n",
						escape(esc, contextId), ZENODOCOMMUNITY_ID_SUFFIX, ID_SEPARATOR, escape(esc, String.valueOf(zc.getId())), escape(esc, zc.getZenodoid())));

		sb.append(paramXML(CZENODOCOMMUNITY_ID, zc.getZenodoid()));
		sb.append("</concept>\n");
		return sb.toString();
	}


	public static String asOrganizationXML(final String contextId, CommunityOrganization organization) {
		final Escaper esc = XmlEscapers.xmlAttributeEscaper();
		final StringBuilder sb = new StringBuilder();
		sb.append(
				String.format(
						"<concept claim='false' id='%s%s%s%s' label='%s'>\n",
						escape(esc, contextId), ORGANIZATION_ID_SUFFIX, ID_SEPARATOR, escape(esc, String.valueOf(organization.getId())), escape(esc, organization.getName())));
		sb.append(paramXML(CORGANIZATION_NAME, organization.getName()));
		sb.append(paramXML(CORGANIZATION_LOGOURL, Base64.getEncoder().encodeToString(organization.getLogo_url().getBytes())));
		sb.append(paramXML(CORGANIZATION_WEBSITEURL,Base64.getEncoder().encodeToString(organization.getWebsite_url().getBytes())));
		sb.append("</concept>\n");
		return sb.toString();
	}


	private static String paramXML(final String paramName, final String value) {
		return String.format("<param name='%s'>%s</param>\n", paramName, escape(XmlEscapers.xmlContentEscaper(), value));
	}

	private static String paramXMLNoEscape(final String paramName, final String value) {
		return String.format("<param name='%s'>%s</param>\n", paramName, value);
	}

}
