package eu.dnetlib.data.claims;

/**
 * Created by Eri on 18/11/2015.
 */


import eu.dnetlib.data.claims.entity.Claim;
import eu.dnetlib.data.claims.entity.OpenaireEntity;
import eu.dnetlib.data.claims.entity.Project;
import eu.dnetlib.data.claims.entity.Result;
import eu.dnetlib.data.claims.handler.*;
import eu.dnetlib.data.claims.parser.ExternalRecordParser;
import eu.dnetlib.data.claims.sql.SQLStoreException;
import eu.dnetlib.data.claims.sql.SqlDAO;
import eu.dnetlib.data.claims.sql.SqlStore;
import eu.dnetlib.data.claims.utils.*;
import eu.dnetlib.data.emailSender.EmailSender;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static junit.framework.Assert.assertNotNull;

/**
 * @author eri
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"springContext-claims.xml"})
@PropertySource("springContext-claims.properties")
public class TestClass {
	private Logger log = LogManager.getLogger(this.getClass());


	private SqlDAO sqlDAO;
    private SqlStore sqlStore;

    private QueryGenerator queryGenerator;

    ProjectHandler projectHandler = null;
    DirectIndexHandler directIndexHandler = null;
    FetchProjectHandler fetchProjectHandler = null;
    IndexResultHandler indexResultHandler = null;
    ExternalRecordHandler externalRecordHandler = null;
    ResultHandler resultHandler = null;

    FetchClaimHandler fetchClaimHandler = null;
    ClaimHandler claimHandler = null;
    ClaimValidation claimValidation = null;

    EmailSender emailSender = null;
    ContextUtils contextUtils = null;


    @Before
	public void init() throws Exception {
        Configurator.initialize(new DefaultConfiguration());
        Configurator.setRootLevel(Level.INFO);
        ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/data/claims/springContext-claims.xml");

        directIndexHandler = context.getBean(DirectIndexHandler.class);
        projectHandler = context.getBean(ProjectHandler.class);
        fetchProjectHandler = context.getBean(FetchProjectHandler.class);

        externalRecordHandler = context.getBean(ExternalRecordHandler.class);
        indexResultHandler = context.getBean(IndexResultHandler.class);
        resultHandler = context.getBean(ResultHandler.class);
        claimHandler = context.getBean(ClaimHandler.class);
        sqlDAO = context.getBean(SqlDAO.class);
        sqlStore = context.getBean(SqlStore.class);
        queryGenerator = context.getBean(QueryGenerator.class);
        fetchClaimHandler = context.getBean(FetchClaimHandler.class);
        claimValidation = context.getBean(ClaimValidation.class);

        emailSender = context.getBean(EmailSender.class);
        contextUtils = context.getBean(ContextUtils.class);

        assertNotNull(sqlDAO);

	}
    @Test
    public void testRollback(){
        List <String> commands = new ArrayList<String>();
        commands.add("UPDATE claim SET claimedBy = 'argirok1' WHERE  id = 93");
        commands.add("EXCEPTION");
        commands.add("UPDATE claim SET claimedBy = 'argirok2' WHERE  id = 95");
        try {
            sqlStore.executeUpdateWithRollback(commands);
        } catch (Exception e) {
            log.error("",e);
        }
    }
    @Test
    public void testJson(){
        Claim claim = new Claim();
        Project project= new Project();
        claim.setDate(Calendar.getInstance().getTime());
        claim.setId("claimId");
        claim.setUserMail("claim mail");

        project.setFunderName("EC");
        project.setOpenaireId("openaireID1234");
        project.setName("PrTitle");
        claim.setSource(project);
        Result result = new Result();
        result.setAccessRights("accessRights");
        result.setCollectedFrom("collectedFrom");
        result.setExternalUrl("external_url");
        result.setOpenaireId("openaire_id");
        result.setTitle("title");
        result.setResultType("type");
        result.setMetadataRecord("xmlString");
        claim.setTarget(result);
        System.out.println("test");
        System.out.println(JsonldBuilder.toJsonld(claim));
    }

    @Test
    public void testFetch() throws Exception {

        try {
            List<Claim> claims = null;
            List<String> types= new ArrayList<String>();
//            types.add(ClaimUtils.CONTEXT);
//            types.add(ClaimUtils.PROJECT);
//          types.add(ClaimUtils.DATASET);
            types.add(ClaimUtils.PUBLICATION);


//            claims = fetchClaimHandler.fetchClaimsByUser("argirok_1@hotmail.com",1,0,types, false);
//            claims = fetchClaimHandler.fetchClaimsByContext("egi",100,0,null,"claim.claim_date",false,types,false);
//            claims = fetchClaimHandler.fetchClaimsByContext("egi",100,0,null,"claim.claim_date",false,types,false);
//            (String openaireId, Integer limit, Integer offset, String keyword, String orderField, boolean descending, List<String> types, boolean addCurationInfo) throws Exception, SQLStoreException {
//            claims = fetchClaimHandler.fetchClaimsByUser("argirok@di.uoa.gr",3,0,null,"claim.claim_date",false,types,false);
//
//            claims = fetchClaimHandler.fetchClaimsByProject("corda_______::ab9c77ce02967b24fc9c1a74276e4677",5,0);
//            claims = fetchClaimHandler.fetchClaimsByProject("corda__h2020::94c962e736df90a5075a7f660ba3d7f6",12,0,null, "claim.claim_date",false,types,true);
            //claims = fetchClaimHandler.fetchClaimsByToken("corda__h2020::94c962e736df90a5075a7f660ba3d7f6","argiro@gmail.com",12,0,null, "claim.claim_date",false,types,false);

//            claims = fetchClaimHandler.fetchClaimsByDate("2016-01-14 14:53:50","2016-04-21",10,0);
//            claims = fetchClaimHandler.fetchClaimsByDate("2016-01-14 14:53:50","2017-04-21",10,0,"", "source",true,types, false);
//            // 2016-04-20 14:53:50.276
//            claims = fetchClaimHandler.fetchClaimsByContext("egi::country::gr",5,0,null,"claim.claim_date",false,types);
//            claims = fetchClaimHandler.fetchAllClaims(5,3);
//            claims = fetchClaimHandler.fetchClaimsByResult("od_______233::235960bb401207cb9595a79a1bc8e867",5,0,null, "claim.claim_date",false,types);
//            claims = fetchClaimHandler.fetchClaimsByFunder("fct_________::FCT",5,0);
//            claims= fetchClaimHandler.fetchClaimsByUser("kiatrop@di.uoa.gr",20,0,types);
//            claims = fetchClaimHandler.fetchAllClaims(10,0,"","date",true,types);

            System.out.println(fetchClaimHandler.claims2JSON(claims)+"\n\n\n "+claims.size());
//          Claim claim = fetchClaimHandler.fetchClaimById("5821");
//          System.out.println(fetchClaimHandler.claim2JSON(claim) );
//          System.out.println("ALL:"+fetchClaimHandler.countClaimsByUser("argirok@di.uoa.gr","EGI", types));
          System.out.println("ALL:"+fetchClaimHandler.countClaimsByContext("egi",null, types, null));
//            System.out.println("ALL:"+fetchClaimHandler.countClaimsByProject("corda_______::ab9c77ce02967b24fc9c1a74276e4677",null,types));

//        System.out.println("ALL:"+fetchClaimHandler.countAllClaims("", types));
//                +"\n Project: "+fetchClaimHandler.countClaimsByProject("corda_______::ab9c77ce02967b24fc9c1a74276e4677")+
//                " \n Result:"+fetchClaimHandler.countClaimsByResult("dedup_wf_001::541b1cef0d38d519e98a3b7a5b60bc75")+" \n Context:"+fetchClaimHandler.countClaimsByContext("egi::country::de")
//        +" \n Date:"+fetchClaimHandler.countClaimsByDate("2014-04-14","2015-04-14")+" \n Funder:"+fetchClaimHandler.countClaimsByFunder("fct_________::FCT"));
        } catch (Exception e) {
            log.error("",e);
        } catch (SQLStoreException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testContext(){

        System.out.print(contextUtils.fetchContextById("egi::organisation::uom"));
    }
    @Test
    public void testInsert() throws Exception, SQLStoreException {
 //acm_________::31e0e5e7cbd6e2556336d7e795f55c49
//dedup_wf_001::64ca1e3a4d1590456ad3dd7df8a18cd7
 /*
claimedBy	argirok_1@hotmail.com
sourceId	corda_______::2c37878a0cede85dbbd1081bb9b4a2f8
sourceType	project
sourceCollectedFrom	openaire
sourceAccessRights	OPEN
sourceEmbargoEndDate
targetId	10.1007/978-3-540-76323-9_4
targetType	software
targetCollectedFrom	crossref
targetAccessRights	EMBARGO
targetEmbargoEndDate	2028-11-10T13:55:47.935Z
  */
//        String id=claimHandler.buildAndInsertClaim("argirok_1@hotmail.com", "project", "corda__h2020::94c962e736df90a5075a7f660ba3d7f6", "openaire", "OPEN", null,"software", "10.1007/978-3-540-76323-9_4", "crossref", "EMBARGO","2028-11-10T13:55:47.935Z");
//        String id=claimHandler.buildAndInsertClaim("argirok@di.uoa.gr", "project", "corda__h2020::94c962e736df90a5075a7f660ba3d7f6", "openaire", "OPEN", null,"publication", "0000-0002-9414-646X-21755327", "orcid", "EMBARGO","2028-11-10T13:55:47.935Z");
//        {user:argirok@di.uoa.gr, sourceType:project, sourceId:corda_______::2c37878a0cede85dbbd1081bb9b4a2f8, sourceCollectedFrom:openaire, sourceAccessRights:OPEN, sourceEmbargoDate:null,
//        targetType:publication, targetId:0000-0002-3477-3082-5288650, targetCollectedFrom:orcid, targetAccessRights:OPEN, targetEmbargoDate:null}
//        String id=claimHandler.buildAndInsertClaim("argirok@di.uoa.gr", "project", "corda_______::2c37878a0cede85dbbd1081bb9b4a2f8",  "openaire", "OPEN", null,"publication",                "0000-0002-3477-3082-5288651", "orcid", "OPEN",null, "development_explore");


//        String id=claimHandler.buildAndInsertClaim("argirok@di.uoa.gr", "context", "egi::country::gr",
//                "openaire", null, null,"dataset", "10.4225/41/55A111BDE741C", "datacite", "OPEN","2017-05-01","development_explore");
    }
    @Test
    public void testDelete() throws Exception, SQLStoreException {

//            claimHandler.deleteClaim("argirok@di.uoa.gr","2876");
//        claimHandler.deleteClaim("argirok@di.uoa.gr","3101");
        }

    //@Test fails due to org.postgresql.util.PSQLException: FATAL: database "claimsnewschema" does not exist
	public void testJob() throws Exception, SQLStoreException {
        String selectcountDMFClaims =" Select count(*) from claims  where type='dmf2actions' and xml NOT ILIKE '%<oaf:concept%' ";
        String selectCountConceptClaims =" Select count(*) from claims  where ( type='dmf2actions' or type='updates2actions' ) and xml LIKE '%<oaf:concept%' ";
        String selectCountRelationClaims =" Select count(*) from claims  where type='rels2actions'  ";

        ResultSet rs = sqlDAO.executePreparedQuery(selectCountConceptClaims);

        while(rs.next()) {
            log.info("Concept claims: "+rs.getInt(1));
        }
         rs = sqlDAO.executePreparedQuery(selectCountRelationClaims);

        while(rs.next()) {
            log.info("Relation claims: "+rs.getInt(1));
        }
         rs = sqlDAO.executePreparedQuery("Select count(*) from claim");

        while(rs.next()) {
            log.info("Migrated claims: "+rs.getInt(1));
        }
        rs = sqlDAO.executePreparedQuery("Select count(*) from result");

        while(rs.next()) {
            log.info("Results: "+rs.getInt(1));
        }

	}

    @Test
    public void testHttpRequest() throws Exception {
        SearchUtils searchUtils= new SearchUtils();
        log.info(searchUtils.fetchPublicationXmlFromIndex("doajarticles::eb8a123eb82b25013b0001d0e2d1842b"));
        log.info(searchUtils.fetchDatasetXmlFromIndex("doajarticles::eb8a123eb82b25013b0001d0e2d1842b"));
    }

    @Test
    public void testXpath() throws Exception {
            Result r=indexResultHandler.fetchResultById("dedup_wf_001::88a1eedd1ffce63dccf51d8ce2053c85");
     }

    @Test
    public void testSoftwareXpath() throws Exception {
//        http://scoobydoo.di.uoa.gr:5000/search/software?softwareId=datacite____%3A%3Aabe9e916b29d028789d7ae3c6f79f254
        Result r=indexResultHandler.fetchSoftwareById("datacite____::abe9e916b29d028789d7ae3c6f79f254");
        if(r!=null){
            System.out.println(r.toString());
        }

    }
    @Test
    public void testPublicationXpath() throws Exception {
        Result r=indexResultHandler.fetchPublicationById("od________18::5acd89ab4df2b877a7a208ea2a123a87");
        if(r!=null){
            System.out.println(r.toString());
        }

    }

    @Test
    public void dropClaimTables() throws Exception {
//        sqlDAO.executeUpdateQuery(queryGenerator.generateDeleteClaimTablesQuery());
    }
    @Test
    public void createClaimTables() throws Exception {
//        sqlDAO.executeUpdateQuery(queryGenerator.generateCreateClaimTablesQuery());
    }
    @Test
    public void printCreateClaimTablesQuery() throws Exception {
        System.out.println(queryGenerator.generateCreateClaimTablesQuery());
    }

    @Test
    public void buildProject() throws Exception {
        String id = "arc_________::089188bbc5db213fb2b00a0d93043fc4";
        Project pr = projectHandler.fetchProjectByID(id);
        log.info(pr.toString());
        id="corda_______::404d91e07cd4d32fddd8fc636ad4daf7";
        pr = projectHandler.fetchProjectByID(id);
        log.info(pr.toString());

    }


    @Test
    public void buildOpenaireResult() throws Exception {


        OpenaireEntity r= claimHandler.buildOpenaireEntity("dedup_wf_001::9e19149f2ece7129e63638a6a52cf468",ClaimUtils.DATASET,ClaimUtils.OPENAIRE,null, null, "");
        log.info(r);

    }
    @Test
    public void buildOpenaireProject() throws Exception {
        String projetcId = "corda_______::2c37878a0cede85dbbd1081bb9b4a2f8";
        OpenaireEntity r= claimHandler.buildOpenaireEntity(projetcId,ClaimUtils.PROJECT,ClaimUtils.OPENAIRE,null, null, "");
        log.info(r);

    }
    //@Test org.postgresql.util.PSQLException: FATAL: database "claimsnewschema" does not exist
    public void testProject() throws Exception, SQLStoreException {
//        List<String> mails = new ArrayList<String>();
//        mails.add("test1@mail.com");
//        mails.add("test2@mail.com");
//        mails.add("test3@mail.com");
//        sqlDAO.executePreparedQuery(queryGenerator.generateInsertProjectQuery("123","test project","TEstP","","","",mails));
        System.out.println("\n"+this.fetchProjectHandler.fetchContactEmailsByProjectId("corda__h2020::94c962e736df90a5075a7f660ba3d7f6")+"\n");
        List<String> mails = new ArrayList<String>();
        mails.add("test11111@mail.com");
        mails.add("test122222@mail.com");
        this.projectHandler.updateContactEmailsByProjectId("123",mails);
//        System.out.println("\n"+this.projectHandler.fetchContactEmailsByProjectId("123")+"\n");
//        String token = UUID.randomUUID().toString();
//        this.projectHandler.updateTokenByProjectId("123",token);



    }
    @Test
    public void testMD5() throws Exception {
        String id = "10.1016/j.engstruct.2013.03.014";
        String createdId = ExternalRecordParser.createOpenaireId(id+ (new Date()).getTime());
        String openaireId = "userclaim___::07ec9eb2278a11e352e3fa93a621411d";
        System.out.println(createdId );

    }
    @Test
    public void testCuration() throws Exception, SQLStoreException {
//        boolean updated = claimHandler.updateClaimCurationInfo("argiro@gmail.com","1",true);
//        System.out.println(updated);
    }
/*
    @Test
    public void testFetchProjectIdByTokenAndEmail() throws Exception, SQLStoreException {
        String openaireId = this.fetchProjectHandler.fetchProjectIdByTokenAndEmail("dedc6979-1967-4ea2-a2ad-5135f95285ae", "test11111@mail.com");
        System.out.println(openaireId);
    }

    @Test
    public void testFetchProjectIdByToken() throws Exception, SQLStoreException {
        String openaireId = this.fetchProjectHandler.fetchProjectIdByToken("dedc6979-1967-4ea2-a2ad-5135f95285ae");
        System.out.println(openaireId);
    }
*/
    @Test
    public void directIndexClaim() throws Exception {
        System.out.println(this.claimValidation.getPathToSaveReport());
        String json = "{\"originalId\":\"userclaim____::d1e668dc81fa714aa98a558d9ce515fa\",\"title\":\"Expression of Ik6 and Ik8 Isoforms and Their Association with Relapse and Death in Mexican Children with Acute Lymphoblastic Leukemia\",\"authors\":[\"Reyes-León Adriana\",\"Juárez-Velázquez Rocío\",\"Medrano-Hernández Alma\",\"Cuenca-Roldán Teresa\",\"Salas-Labadía Consuelo\",\"del Pilar Navarrete-Meneses María\",\"Rivera-Luna Roberto\",\"López-Hernández Gerardo\",\"Paredes-Aguilera Rogelio\",\"Pérez-Vera Patricia\"],\"publisher\":\"Public Library of Science (PLoS)\",\"type\":\"publication\",\"pids\":[{\"type\":\"doi\",\"value\":\"10.1371/journal.pone.0130756\"}],\"licenseCode\":\"OPEN\",\"resourceType\":\"0001\",\"url\":\"http://dx.doi.org/10.1371/journal.pone.0130756\",\"hostedById\":\"openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18\",\"collectedFromId\":\"openaire____::crossref\",\"contexts\":[\"egi::country::gr\"]}";
//        System.out.println("\n\nFeed Response is: "+directIndexHandler.insertRecord(json));

//        System.out.println("\n\nDelete Response is: "+directIndexHandler.deleteRecord("userclaim___::d1e668dc81fa714aa98a558d9ce515fa","openaire____::crossref"));
    }

    // To run following tests about email: claim notifications, set all the properties inside project folder
    @Test
    public void forceSendEmailNotifications() throws Exception {
        //emailSender.run();
    }

    @Test
    public void testEmail() throws Exception {
        ArrayList<String> list = new ArrayList<String>();
        list.add("konstantinagalouni@gmail.com");
        list.add("argirok@di.uoa.gr");
//        emailSender.send("openaire_id_test", "openaire_name_test", "community", list);
    }

    @Test
    public void testDeleteQuery() throws Exception {
        ArrayList<String> types = new ArrayList<>();
//        types.add("project");
//        types.add("context");
        ArrayList<Object> x = new ArrayList<>();
        System.out.println(this.queryGenerator.generateFetchClaimsByUser("TEST", 10,0,"_search_keyword_","date",true,types,x));
//        System.out.println(this.queryGenerator.generateFetchClaimsByContext("covid-19", 10,0,null,"date",true,types,x));
        System.out.println(x);
    }

}
