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

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Objects;

public class ValueRangeCalibrationModel extends Model {

    private static final Logger LOGGER = LoggerFactory.getLogger(ValueRangeCalibrationModel.class);

    private Table<Double, Double, Double> table = HashBasedTable.create();

    @Override
    public int getModelSize() {
        return table.size();
    }

    @Override
    public boolean loadFromStream(InputStreamReader in) throws Exception {
        Table<Double, Double, Double> initTable = HashBasedTable.create();
        try (BufferedReader input = new BufferedReader(in)) {
            String line;
            while ((line = input.readLine()) != null) {
                String[] items = line.split("\t");
                if (items.length < 2) {
                    continue;
                }

                String[] scores = items[0].replaceAll("[(\\]]", "").split(",");

                initTable.put(Double.parseDouble(scores[0]), Double.parseDouble(scores[1]), Double.parseDouble(items[1]));

            }

            this.table = initTable;

            for (Table.Cell<Double, Double, Double> cell : this.table.cellSet()) {
                LOGGER.info("[ValueRangeCalibrationModel] cell.row: {}, cell.column: {}, cell.value: {}", cell.getRowKey(), cell.getColumnKey(), cell.getValue());
            }

            LOGGER.info("[ValueRangeCalibrationModel] model load over and size {}", this.table.size());
        } catch (Exception e) {
            LOGGER.info("[ValueRangeCalibrationModel] model load error ", e);
        } finally {
            in.close();

        }
        return true;
    }

    public Double getDiffRate(double score) {
        if (Objects.isNull(table)) {
            return 0d;
        }

        for (Table.Cell<Double, Double, Double> cell : table.cellSet()) {
            double rowKey = cell.getRowKey();
            double columnKey = cell.getColumnKey();
            if (rowKey < score & score <= columnKey) {
                LOGGER.info("score {} in {} - {} , value is {}", score, rowKey, columnKey, cell.getValue());
                return cell.getValue();
            }
        }

        return 0d;
    }
}
