package com.tzld.piaoquan.recommend.server.service.score4recall.model4recall;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Model4RecallLongTerm extends AbstractModel {
    private static final Logger LOGGER = LoggerFactory.getLogger(Model4RecallLongTerm.class);
    public Map<String, List<Pair<Long, Double>>> kv;
    public Model4RecallLongTerm() {
        this.kv = new HashMap<>();
    }

    @Override
    public boolean loadFromStream(InputStreamReader in) throws IOException {
        BufferedReader input = new BufferedReader(in);
        String line = null;
        while ((line = input.readLine()) != null) {
            String[] items = line.split("\t");
            if (items.length < 3) {
                continue;
            }
            String key = items[0].trim();
            long l1 = 0L;
            double l2 = 0D;
            try{
                l1 = Long.parseLong(items[1]);
                l2 = Double.parseDouble(items[2]);
            }catch (Exception e){
                LOGGER.error(String.format("something is wrong with parse pair in Model4RecallLongTerm %s %s: ", items[1], items[2]), e);
                continue;
            }
            List<Pair<Long, Double>> list = this.kv.getOrDefault(key, new ArrayList<>());
            list.add(Pair.of(l1, l2));
            this.kv.put(key, list);
        }
        input.close();
        in.close();
        kv.forEach((key, value) ->
                value.sort((p1, p2) -> Double.compare(p2.getRight(), p1.getRight()))
        );
        return true;
    }
}