package eu.dnetlib.statsapi.repositories;

import eu.dnetlib.statsapi.domain.Funder;
import eu.dnetlib.statsapi.domain.Result;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

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

@Repository
public class FunderRepository {

    private RedisTemplate<String, String> redisTemplate;

    private HashOperations<String, String, String> jedis;

    private final Logger log = Logger.getLogger(this.getClass());

    public FunderRepository(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.jedis = this.redisTemplate.opsForHash();
    }

    public Result getFunder(String funder) {
        Boolean not_found = true;
        ArrayList<String> items = new ArrayList<>();
        items.add(funder.toLowerCase() + "pubstotal");
        items.add(funder.toLowerCase() + "oapubs");
        items.add(funder.toLowerCase() + "embpubs");
        items.add(funder.toLowerCase() + "respubs");
        items.add(funder.toLowerCase() + "projtotal");
        items.add(funder.toLowerCase() + "projpubs");

        List<String> result = jedis.multiGet("STATS_NUMBERS", items);
        int pubs = 0, oa = 0, emb = 0, res = 0, proj = 0, proj_pubs = 0;
        if (result.get(0) != null) {
            pubs = Integer.parseInt(result.get(0).replaceAll(",", ""));
            not_found = false;
        }
        if (result.get(1) != null) {
            oa = Integer.parseInt(result.get(1).replaceAll(",", ""));
            not_found = false;
        }
        if (result.get(2) != null) {
            emb = Integer.parseInt(result.get(2).replaceAll(",", ""));
            not_found = false;
        }
        if (result.get(3) != null) {
            res = Integer.parseInt(result.get(3).replaceAll(",", ""));
            not_found = false;
        }
        if (result.get(4) != null) {
            proj = Integer.parseInt(result.get(4).replaceAll(",", ""));
            not_found = false;
        }
        if (result.get(5) != null) {
            proj_pubs = Integer.parseInt(result.get(5).replaceAll(",", ""));
            not_found = false;
        }

        if (not_found) {
            return new Result("Not Found", "400", null);
        }

        return new Result("OK", "200", new Funder(pubs, oa, emb, res, proj, proj_pubs));
    }
}
