package eu.dnetlib.repo.manager.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.dnetlib.domain.data.PiwikInfo;
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Types;
import java.util.List;
import java.util.Map;

@Service("piwikService")
public class PiWikServiceImpl implements PiWikService {

    @Qualifier("repomanager.dataSource")
    @Autowired
    private DataSource dataSource;


    @Value("${services.repomanager.analyticsURL}")
    private String analyticsURL;


    @Autowired
    @Qualifier("emailUtils")
    EmailUtils emailUtils;

    private static final Logger LOGGER = Logger
            .getLogger(PiWikServiceImpl.class);

    private final static String GET_PIWIK_SITE = "select repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site where repositoryid = ?;";

    private final static String INSERT_PIWIK_INFO = "insert into piwik_site (repositoryid, siteid, creationdate, requestorname, requestoremail, validated, repositoryname, country, authenticationtoken) values (?, ?, now(), ?, ?, ?, ?, ?, ?)";

    private final static String GET_PIWIK_SITES = "select repositoryid, siteid, authenticationtoken, creationdate, requestorname, requestoremail, validated, validationdate, comment, repositoryname, country from piwik_site order by repositoryname";

    private final static String APPROVE_PIWIK_SITE = "update piwik_site set validated=true, validationdate=now() where repositoryid = ?;";



    private RowMapper<PiwikInfo> piwikRowMapper = (rs, i) -> new PiwikInfo(rs.getString("repositoryid"), getOpenaireId(rs.getString("repositoryid")), rs.getString("repositoryname"), rs.getString("country"),
            rs.getString("siteid"), rs.getString("authenticationtoken"), rs.getTimestamp("creationdate"), rs.getString("requestorname"), rs.getString("requestoremail"),
            rs.getBoolean("validated"), rs.getTimestamp("validationdate"), rs.getString("comment"));


    @Override
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
        try{
            return new JdbcTemplate(dataSource).queryForObject(GET_PIWIK_SITE, new String[]{repositoryId}, new int[]{Types.VARCHAR}, piwikRowMapper);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update(INSERT_PIWIK_INFO, new Object[]{piwikInfo.getRepositoryId(), piwikInfo.getSiteId(), piwikInfo.getRequestorName(),
                        piwikInfo.getRequestorEmail(), piwikInfo.isValidated(), piwikInfo.getRepositoryName(), piwikInfo.getCountry(), piwikInfo.getAuthenticationToken()},
                new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
        return piwikInfo;
    }

    @Override
    public List<PiwikInfo> getPiwikSitesForRepos() {
        LOGGER.debug("Getting piwik sites for repos! ");
        try{
            return new JdbcTemplate(dataSource).query(GET_PIWIK_SITES, piwikRowMapper);
        }catch (EmptyResultDataAccessException e){
            return null;
        }

    }

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
    public ResponseEntity<Object> approvePiwikSite(@PathVariable("repositoryId") String repositoryId) {
        new JdbcTemplate(dataSource).update(APPROVE_PIWIK_SITE, new Object[] {repositoryId}, new int[] {Types.VARCHAR});
        return new ResponseEntity<>("OK",HttpStatus.OK);
    }

    @Override
    public String getOpenaireId(@PathVariable("repositoryId") String repositoryId) {
        if (repositoryId != null && repositoryId.contains("::"))
            return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
        return null;
    }

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
    public ResponseEntity<Object> markPiwikSiteAsValidated(@PathVariable("repositoryId") String repositoryId) throws RepositoryServiceException {
        try {
            approvePiwikSite(repositoryId);

            PiwikInfo piwikInfo = getPiwikSiteForRepo(repositoryId);
            emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
            emailUtils.sendUserMetricsEnabled(piwikInfo);

        } catch (EmptyResultDataAccessException e) {
            LOGGER.error("Error while approving piwik site: ", e);
            emailUtils.reportException(e);
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
        } catch (Exception e) {
            LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
            emailUtils.reportException(e);
        }
        return new ResponseEntity<>("OK",HttpStatus.OK);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
    public PiwikInfo enableMetricsForRepository(@RequestParam("officialName") String officialName,
                                                @RequestParam("repoWebsite") String repoWebsite,
                                                @RequestBody PiwikInfo piwikInfo) throws RepositoryServiceException {
        try {
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(officialName, "UTF-8") + "&url="
                    + URLEncoder.encode(repoWebsite, "UTF-8");
            Map map = new ObjectMapper().readValue(new URL(URL), Map.class);
            String siteId = null;
            if(map.get("value")!=null) {
                siteId = map.get("value").toString();
            }
            piwikInfo.setSiteId(siteId);

            savePiwikInfo(piwikInfo);
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
        } catch (UnsupportedEncodingException uee) {
            LOGGER.error("Error while creating piwikScript URL", uee);
            emailUtils.reportException(uee);
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
        } catch (IOException ioe) {
            LOGGER.error("Error while creating piwik site", ioe);
            emailUtils.reportException(ioe);
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
        } catch (Exception e) {
            LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e);
            emailUtils.reportException(e);
        }
        return piwikInfo;
    }


}
