class AppPage {
    constructor() {

        this.TaskNumber = 0;

        this.api = new ApiProvider();
        


        this.div_task = document.getElementById('div_Task');
        this.div_UserView = document.getElementById('View_User');
        this.text_UserCss = document.getElementById('User_CSS');
        this.block_style = document.getElementById('style');
        this.block_result = document.getElementById('Validate');

        this._OnClick_ButtonSet = this._OnClick_ButtonSet.bind(this);
        this._OnClick_ButtonValidate = this._OnClick_ButtonValidate.bind(this);
        this._OnClick_ButtonTask = this._OnClick_ButtonTask.bind(this);

        document.getElementById('Button_SetCss').onclick = this._OnClick_ButtonSet;
        document.getElementById('Button_Validate').onclick = this._OnClick_ButtonValidate;

        this.LoadTask();

        this.taskMenuControl = new TaskMenuControl(this._OnClick_ButtonTask);
    }


    LoadTask() {
        this.api.GetTask(this.TaskNumber).then(e => {

            this.div_task.innerHTML = e.HTML_Text;
            this.div_UserView.innerHTML = e.HTML_Template;
            this.text_UserCss.value = e.CSS_Template;
        });
    }

    

    //Костыльный конвертер
    ConvertCSS(css) {
        let res = {};

        for (let i = 0; i < css.length; i++) {
            let key = css[i];
            let value = css[key];

            res[key] = value;
        }

        return res;
    }

    _OnClick_ButtonTask(ID) {
        if (this.TaskNumber === ID)
        {
            return;
        }

        this.block_result.value = "";
        this.TaskNumber = ID;
        this.LoadTask();
    }

    _OnClick_ButtonSet() {

        this.block_style.innerHTML = this.text_UserCss.value;
    }

    _OnClick_ButtonValidate() {
        let elements = this.div_UserView.children;
        let elem_styles = [];

        for (let i = 0; i < elements.length; i++) {
            let elem_style = window.getComputedStyle(elements[i]);
            elem_styles.push(this.ConvertCSS(elem_style));
        }

        this.api.Validate(this.TaskNumber, elem_styles)
            .then(e => {

                if (e) {
                    this.block_result.value = "Решение верно";
                }
                else {
                    this.block_result.value = "Решение не верно";
                }
                
            });
    }

}