package com.tzld.piaoquan.ad.engine.commons.score.model;

import com.tzld.piaoquan.recommend.feature.domain.ad.base.AdRankItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeMap;


public class CalibrationModel extends Model {
    protected static final int MODEL_FIRST_LOAD_COUNT = 1 << 25;  // 32M
    private static final Logger LOGGER = LoggerFactory.getLogger(CalibrationModel.class);

    private TreeMap<Double, Double> calibrationModel;

    public CalibrationModel() {
        //配置不同环境的hdfs conf
        this.calibrationModel = new TreeMap<>();
    }

    public TreeMap<Double, Double> getCalibrationModel() {
        return this.calibrationModel;
    }


    @Override
    public boolean loadFromStream(InputStreamReader in) throws IOException {
        TreeMap<Double, Double> bins = new TreeMap<>();
        BufferedReader input = new BufferedReader(in);
        String line = null;
        int cnt = 0;
        while ((line = input.readLine()) != null) {
            String[] items = line.split("\t");
            if (items.length < 2) {
                continue;
            }
            bins.put(Double.parseDouble(items[0]), Double.parseDouble(items[1]));
        }

        this.calibrationModel = bins;
        LOGGER.info("[MODELLOAD] calibration model load over and size " + cnt);
        input.close();
        in.close();
        return true;
    }


    @Override
    public int getModelSize() {
        if (this.calibrationModel == null)
            return 0;
        int sum = this.calibrationModel.size();
        return sum;
    }

    public double score(AdRankItem adRankItem, String ctrOrCVR) {
        double score = 0.0f;
        if (ctrOrCVR.equals("ctr")) {
            double upperBound = this.calibrationModel.floorKey(adRankItem.getCtr());
            score = this.calibrationModel.get(upperBound);
        }
        if (ctrOrCVR.equals("cvr")) {
            double upperBound = this.calibrationModel.floorKey(adRankItem.getCvr());
            score = this.calibrationModel.get(upperBound);
        }
        return score;
    }

}
