export class Sampler {


    constructor(id, data, classes, investment, maxSamples) {
        this.data = data;
        this.samples = [];
        this.classes = classes;
        this.id = id;
        this.investment = investment;
        this.svgclass = 'sampler-' + this.id;
        this.currentSample = { cid: undefined, yield: 0, id: undefined };
        this.maxSamples = maxSamples;
        this.THIN_SPACE = '\u2009';
    }

    // actual sampling implemented as importance sampling in sampling app
    drawSample(idx) {

        let d = this.data[idx];
        let y = this.investment.ratio * d.values[0] + (1 - this.investment.ratio) * d.values[1];  // yield (percentage)
        let c = (y + 1) * this.investment.input.value;  // calculate absolute result (input + yield)
        let classid;

        if (c >= this.investment.output.value) {
            classid = this.classes[1].id;
        } else {
            classid = this.classes[0].id;
        }

        this.currentSample = {
            cid: classid,
            yield: y,
            id: this.samples.length
        };

        this.samples.push(this.currentSample);
    }

    getCalculatedYield() {
        let factor = Math.pow(10, 0);
        let val = Math.round(this.currentSample.yield * 100 * factor) / factor;
        let sign = '';
        if (val > 0) {
            sign = '+';
        } else if (sign < 0) {
            sign = '-';
        }

        let result = (sign + val + this.THIN_SPACE + '%').replace('.', ',');
        return result;
    }

    get calculatedYield() {
        return this.getCalculatedYield();
    }

    getLeftOptionRatioRepr() {
        let val = Math.round(this.investment.ratio * 100000) / 1000;
        return val + this.THIN_SPACE + '%';
    }

    get leftOptionRatioRepr() {
        return this.getLeftOptionRatioRepr();
    }

    getRightOptionRatioRepr() {
        let val = Math.round((1 - this.investment.ratio) * 100000) / 1000;
        return val + this.THIN_SPACE + '%';
    }

    get rightOptionRatioRepr() {
        return this.getRightOptionRatioRepr();
    }

    setPeriod(val) {
        this.period = val;
    }

    setCurrentSample(idx) {
        if (this.samples.length - 1 >= idx) {
            this.currentSample = this.samples[idx];
        }
    }

    samplesPerClass() {
        let samplesIsolated = [];
        let samples = [];
        for (let s of this.samples) {  // deep copy of samples
            samples.push(s);
        }

        for (let cls of this.classes) {
            let arr = samples.filter(function(c) {
                return c.cid === cls.id;
            }, cls);

            samplesIsolated.push(arr);
        }
        return samplesIsolated;
    }

    reset() {
        this.samples = [];
        this.currentSample = { cid: undefined, yield: 0, id: undefined };
    }
}
