import {Api, XMLOperate, Helper} from '../../utility';
import Tree from './Tree';

class Modal {
    constructor(target, container, report) {
        this.target = target;
        this.container = container;
        this.report = report;
        this.api = new Api();
    }

    setProps(newProps) {
        Object.assign(this, newProps);
    }

    getProp(prop) {
        return this[prop];
    }

    render() {
        const $container = $(this.container);
        const $target = $(this.target);
        const report = this.report;
        const api = this.api;

        if(!$container || !$target || !report) {
            throw new Error('container or target or report lose');
        } else {
            if($target.attr('id') == 'showCode') {
                const xml = report.toXML();

                api.getTemplete('showCodeModal-tmpl').done((tml) => {
                    const $html = Helper.getInstance().handleTemplete(tml,{xml}, 'showCodeModal-tmpl');
                    $container.html($html);
                });
            } else if($target.attr('data-id') == 'showEditor') {
                $.when(api.getTemplete('editorModal-tmpl'), api.getJSON()).done((tml, data) => {
                    const $html = Helper.getInstance().handleTemplete(tml[0], data[0], 'editorModal-tmpl');
                    $container.html($html);
                });
            }

            this.bindEvent();
        }
    }

    bindEvent() {
        const $container = $(this.container);
        const tree = Tree.getInstance();
        const report = this.report;

        $container.off('click', '#xmlTextConfirm').on('click', '#xmlTextConfirm', function(e) {
            const xmlString = $container.find("#xmlCode").val();
            const parse = new DOMParser();
            const xmldoc = parse.parseFromString(xmlString, 'text/xml');

            new XMLOperate(xmldoc, report).parserXML();
            report.resetChunkBaseline();
            report.paint();
            tree.render();
        });
    }

}

export default Modal;