"use strict";

import {resizeContainerAndCanvas, BigSlider, Slider} from "../../modules/HTMLUtils.js";
import CtxUtils from "../../modules/Context2DUtils.js";
import V2 from "../../modules/V2.js"; 

/**
 * Gráfica del factor de atenuación.
 * @author Melissa Méndez Servín.
 */
window.addEventListener("load", main);

function main(){
    
    let controls = document.getElementById("ui-container");
    controls.className = "right-box";
    const colorsSlider = ["#4994D0", "#C6C6B2"];
    var A = 1;
    var B = 0;
    var C = 0;
    let a_slider = new Slider(controls, "a", 0, 100, updateCoeff(0), A, .01, colorsSlider);
    let b_slider = new Slider(controls, "b", 0, 100, updateCoeff(1), B, .01, colorsSlider);
    let c_slider = new Slider(controls, "c", 0, 100, updateCoeff(2), C, .01, colorsSlider);

    var canvas = document.getElementById("canvas");
    var origin, axes;
    const NUM_POINTS_CURVE = 200;
    const MAX_DISTANCE = 9;

    window.addEventListener('resize', draw);
    draw();

    function draw(){
        let scale = 60 * resizeContainerAndCanvas(canvas);
        CtxUtils.clear();

        let {width, height} = canvas;
        origin = new V2(.05 * width, .96 * height); 
        axes = { origin: origin, x: new V2(origin.x,  origin.x + scale * MAX_DISTANCE), y: new V2(origin.y, .1 * height)};
        CtxUtils.drawAxes(axes, 2);
        drawAttenuationCurve(origin.x, origin.y, scale, .05 * height);
    }
    function drawAttenuationCurve(center, height, amplitud, top){
        const ratio = MAX_DISTANCE/2/NUM_POINTS_CURVE;
        const ratio2 = MAX_DISTANCE/NUM_POINTS_CURVE;
         function attenuation(d){
            return 1/((A*d**2) + (B*d) + C);
        }
        let start = ratio;
        var y = height - attenuation(start) * amplitud;
        var x = center;
        CtxUtils.ctx.beginPath();
        CtxUtils.ctx.lineWidth = 2.2;
        CtxUtils.ctx.strokeStyle = "#00BBD0";
        var i = start + ratio;
        while(i<= MAX_DISTANCE){
            y = height - attenuation(i) * amplitud;
            x= center + i * amplitud;
            if(y > top){
                CtxUtils.ctx.lineTo(x, y);
                y = height - attenuation(i) * amplitud;
                x = center + i * amplitud;
                CtxUtils.ctx.moveTo(x, y);
            }
            i = (i > MAX_DISTANCE/2) ? i + ratio2 : i + ratio;
        }
        CtxUtils.ctx.stroke();
        CtxUtils.ctx.strokeStyle = "black";
    };
    function updateCoeff(index){
        return function(value){
            switch(index){
                case 0:
                    A = value;
                    break;
                case 1: 
                    B = value;
                    break;
                case 2:
                    C = value;
                    break;
            }    
            draw();
        }
    }
}
