/**
 * Created by eri_k on 2/20/2016.
 */
package eu.dnetlib.usagestats.repos;


import eu.dnetlib.usagestats.domain.UsageStats;
import org.apache.log4j.Logger;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;


@RepositoryRestResource(collectionResourceRel = "datasourceStats", path = "datasourceStats")
@Repository
public class DatasourceRepo extends BaseRepository {

    private Logger log = Logger.getLogger(this.getClass());


    public UsageStats getClicks(String id) {

        String query = "select d.id, d.name , sum (ds.numberofviews) from datasource d, usagestats.datasourcesstats ds " +
                "where ds.datasourceid=d.id and d.id=? group by d.id, d.name;";

        List<String> values = new ArrayList<String>();
        values.add(id);

        List<UsageStats> results = executePreparedQuery(query, values);
        if (!results.isEmpty()) return results.get(0);

        return new UsageStats();

    }


    public List<UsageStats> getMostPopular() {
        String query = "select d.id, d.name , sum (ds.numberofviews) from datasource d, usagestats.datasourcesstats ds where " +
                "ds.datasourceid=d.id group by d.id, d.name order by  sum (ds.numberofviews)  desc limit 10;";

        return executeQuery(query);
    }

    public List<UsageStats> getMostPopularPubs(String datasourceId) {

        String query = "select r.id, r.title , sum(rs.numberofviews) from result r, usagestats.resultsstats rs, result_datasources rd  where r.id=rd.id and rd.datasource=? and  rs.resultid=r.id group by r.id, r. title order by  sum(rs.numberofviews)  desc limit 10;";


        List<String> values = new ArrayList<String>();
        values.add(datasourceId);
        return executePreparedQuery(query, values);

    }


    public List<UsageStats> getMostPopularProjects(String datasourceId) {

        String query = "select p.id, p.title, sum(ps.numberofviews)  from project p, result_datasources rd, project_results pr , usagestats.projectsstats ps " +
                " where  rd.datasource=? and  p.id=pr.id and pr.result=rd.id  and ps.projectid=p.id " +
                " group by p.id, p.title order by sum (ps.numberofviews) desc limit 10;";
        List<String> values = new ArrayList<String>();
        values.add(datasourceId);
        return executePreparedQuery(query, values);

    }

    public List<UsageStats> getPopularityOverTime(String datasourceId) {

        String query = "select ds.datasourceid, ds.timestamp_month , ds.numberofviews from usagestats.datasourcesstats ds " +
                " where ds.datasourceid=?  order by ds.timestamp_month  desc ;";
        List<String> values = new ArrayList<String>();
        values.add(datasourceId);
        return executePreparedQuery(query, values);

    }


}


