"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Board_1 = require("./Board");
var MooBase_1 = require("./base/MooBase");
var CreateDOM_1 = require("../utils/CreateDOM");
var defaultFiles_1 = require("./defaultFiles");
var types_1 = require("../types");
var lz_string_1 = __importDefault(require("lz-string"));
var Exceptions_1 = require("../utils/Exceptions");
var CodeRunner = /** @class */ (function (_super) {
    __extends(CodeRunner, _super);
    // NOTE  make this interface to avoid module dependencies
    function CodeRunner(CodeBoard) {
        var _this = _super.call(this, CodeBoard.ele) || this;
        _this._isEmbeded = false;
        // checkbox
        _this._createEmbededCheckbox(_this.ele);
        // iframe closeButton
        var closeButton = CreateDOM_1.CreDOM.createDOM('button', 'r-coderunner-close-button');
        _this._iframeCloseButton = closeButton;
        closeButton.textContent = 'close';
        closeButton.style.display = 'none';
        _this._helloListener(types_1.CLICK, _this._closeRunner.bind(_this), closeButton);
        _this.ele.appendChild(closeButton);
        // iframe container
        var iframe = CreateDOM_1.CreDOM.createDOM('div', 'r-coderunner-iframe-container');
        _this._frame = iframe;
        CodeBoard.ele.appendChild(iframe);
        return _this;
    }
    CodeRunner.prototype._createElement = function () {
        var ele = CreateDOM_1.CreDOM.createDOM('div', 'r-coderunner');
        var button = CreateDOM_1.CreDOM.createDOM('button', 'r-coderunner-button');
        button.textContent = 'Test!';
        this._button = button;
        ele.appendChild(button);
        return ele;
    };
    Object.defineProperty(CodeRunner.prototype, "button", {
        get: function () {
            return this._button;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CodeRunner.prototype, "isEmbeded", {
        get: function () {
            return this._isEmbeded;
        },
        set: function (isEmbeded) {
            this._isEmbeded = isEmbeded;
            var checkbox = this._embededCheckbox;
            checkbox.checked = isEmbeded;
        },
        enumerable: true,
        configurable: true
    });
    CodeRunner.prototype._createEmbededCheckbox = function (container) {
        var _this = this;
        var label = CreateDOM_1.CreDOM.createDOM('label', 'r-codeboard-embeded-checkbox-label');
        var checkbox = CreateDOM_1.CreDOM.createDOM('input', 'r-codeboard-embeded-checkbox');
        checkbox.type = 'checkbox';
        var textNode = document.createTextNode('Embeded?');
        label.appendChild(checkbox);
        label.appendChild(textNode);
        this._embededCheckbox = checkbox;
        var callback = function (event) {
            var target = event.target;
            _this._isEmbeded = target.checked;
        };
        this._helloListener(types_1.CLICK, callback, checkbox);
        container.appendChild(label);
    };
    CodeRunner.prototype._closeRunner = function (event) {
        this._iframeCloseButton.style.display = 'none';
        this._frame.innerHTML = '';
    };
    CodeRunner.prototype._determineEnv = function (preset) {
        if (preset === types_1.PresetType.STATIC) {
            return __assign(__assign({}, defaultFiles_1.defaultPackageJson), defaultFiles_1.staticEnvSandbox);
        }
        else {
            throw new Error('This type is not supported: ' + preset);
        }
    };
    CodeRunner.prototype._convertToParam = function (filesCon) {
        var compress = function (object) {
            return lz_string_1.default.compressToBase64(JSON.stringify(object))
                .replace(/\+/g, '-') // Convert '+' to '-'
                .replace(/\//g, '_') // Convert '/' to '_'
                .replace(/=+$/, ''); // Remove ending '='
        };
        var env = this._determineEnv(this._presetType);
        var param = {
            files: __assign(__assign({}, filesCon), env)
        };
        var parameters = compress(param);
        return parameters;
    };
    CodeRunner.prototype.requestCode = function (files, presetType, runner) {
        var _this = this;
        this._presetType = presetType;
        if (runner === types_1.RunnerType.CSB) {
            var params = this._convertToParam(files);
            var data_1;
            if (this._isEmbeded) {
                this._iframeCloseButton.style.display = 'inline';
                var url = "https://codesandbox.io/api/v1/sandboxes/define?json=1&parameters=" + params;
                var httpRequest_1;
                var request = function (url) {
                    httpRequest_1 = new XMLHttpRequest();
                    httpRequest_1.onreadystatechange = reqListener_1;
                    httpRequest_1.open("GET", url);
                    httpRequest_1.send();
                };
                var reqListener_1 = function () {
                    if (httpRequest_1.readyState === XMLHttpRequest.DONE) {
                        if (httpRequest_1.status === 200) {
                            data_1 = JSON.parse(httpRequest_1.responseText);
                            console.log(data_1.sandbox_id);
                            _this._frame.innerHTML = "<iframe\n                            src=\"https://codesandbox.io/embed/test-" + data_1.sandbox_id + "?fontsize=14&hidenavigation=1&theme=dark\"\n                            style=\"width:100%; height:100%; border:0; border-radius: 4px; overflow:hidden;\"\n                            title=\"test\"\n                            allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n                            sandbox=\"allow-embededs allow-forms allow-popups allow-scripts allow-same-origin\"\n                          ></iframe>";
                        }
                    }
                };
                request(url);
            }
            else {
                var url = "https://codesandbox.io/api/v1/sandboxes/define?parameters=" + params;
                window.open(url);
            }
        }
    };
    CodeRunner.prototype.getURL = function (files, presetType, runner) {
        this._presetType = presetType;
        if (runner === types_1.RunnerType.CSB) {
            var params = this._convertToParam(files);
            var url = "https://codesandbox.io/api/v1/sandboxes/define?parameters=" + params;
            return url;
        }
    };
    return CodeRunner;
}(MooBase_1.MooBase));
exports.CodeRunner = CodeRunner;
var CodeBoard = /** @class */ (function (_super) {
    __extends(CodeBoard, _super);
    function CodeBoard(container, preset, hasTools) {
        if (hasTools === void 0) { hasTools = true; }
        var _a;
        var _this = _super.call(this, container) || this;
        var opt = (_a = preset) === null || _a === void 0 ? void 0 : _a.otherConfig;
        if (!opt) {
            opt = {};
        }
        _this._isFixedTemplate = opt.isFixedTemplate ? true : false;
        // board
        var board = new Board_1.Board(_this, opt);
        _this._board = board;
        // preset TODO later 분리 runner랑 preset 포함 관계 확실히
        _this._presetType = preset ? preset.type : types_1.PresetType.STATIC;
        _this._runnerType = preset && preset.runner ? preset.runner : types_1.RunnerType.CSB;
        // initialize
        if (preset && preset.files) {
            var files = preset.files;
            _this._board.parseFiles(files);
        }
        else {
            _this._board.createPage(types_1.JS, 'index.js', "console.log('hello world!')");
        }
        // createTools
        if (hasTools) {
            _this._tools = _this._createTools();
        }
        // runner
        var runner = new CodeRunner(_this);
        _this._runner = runner;
        // runner event listener;
        _this._helloListener(types_1.CLICK, _this.runCode.bind(_this), _this._runner.button);
        return _this;
    }
    CodeBoard.prototype._createElement = function () {
        var ele = CreateDOM_1.CreDOM.createDOM('div', 'r-codeboard');
        return ele;
    };
    CodeBoard.prototype._createTools = function () {
        var tools = CreateDOM_1.CreDOM.createDOM('div', 'r-codeboard-tools');
        this.ele.appendChild(tools);
        this._createPresetSelectTool(tools);
        this._createExportButton(tools);
        return tools;
    };
    CodeBoard.prototype._createPresetSelectTool = function (container) {
        var _this = this;
        var select = document.createElement('select');
        select.className = 'r-codeboard-preset-select';
        var callback = function (event) {
            var target = event.target;
            _this._presetType = target.value;
        };
        for (var type in types_1.PresetType) {
            var opt = CreateDOM_1.CreDOM.createDOM('option', 'r-codeboard-preset-type');
            opt.value = type;
            opt.text = type;
            select.appendChild(opt);
            this._helloListener(types_1.CLICK, callback, opt);
        }
        this._presetList = select;
        container.appendChild(select);
    };
    CodeBoard.prototype._createExportButton = function (container) {
        var button = CreateDOM_1.CreDOM.createDOM('button', 'r-codeboard-export-button');
        button.textContent = 'export code';
        this._helloListener(types_1.CLICK, this.exportCode.bind(this), button);
        container.appendChild(button);
    };
    Object.defineProperty(CodeBoard.prototype, "presetType", {
        get: function () {
            return this._presetType;
        },
        set: function (presetType) {
            this._presetType = presetType;
            var presetList = this._presetList;
            // TODO sync with selectTool
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(CodeBoard.prototype, "isEmbeded", {
        get: function () {
            return this._runner.isEmbeded;
        },
        set: function (isEmbeded) {
            this._runner.isEmbeded = isEmbeded;
        },
        enumerable: true,
        configurable: true
    });
    CodeBoard.prototype.runCode = function () {
        var files = this._board.getFiles();
        this._runner.requestCode(files, this._presetType, this._runnerType);
    };
    CodeBoard.prototype.exportCode = function () {
        var files = this._board.getFiles();
        console.log(files);
        return files;
    };
    CodeBoard.prototype.exportCodeByFilename = function (filename) {
        var files = this._board.getFiles();
        return files[filename].content;
    };
    CodeBoard.prototype.exportURL = function () {
        var files = this._board.getFiles();
        return this._runner.getURL(files, this._presetType, this._runnerType);
    };
    CodeBoard.prototype.addFile = function (filename) {
        if (this._isFixedTemplate) {
            this._board.addFile(filename);
        }
        else {
            throw new Exceptions_1.ValidationError('opt', 'locked! because of isFixedTemplate');
        }
    };
    CodeBoard.prototype.addFiles = function (filenames) {
        if (this._isFixedTemplate) {
            if (!Array.isArray(filenames)) {
                throw new Exceptions_1.ValidationError('array', 'The parameter is not array. please, check the api.');
            }
            this._board.addFiles(filenames);
        }
        else {
            throw new Exceptions_1.ValidationError('opt', 'locked! because of isFixedTemplate');
        }
    };
    CodeBoard.prototype.removeFile = function (filename) {
        if (this._isFixedTemplate) {
            this._board.removeFile(filename, true);
        }
        else {
            throw new Exceptions_1.ValidationError('opt', 'locked! because of isFixedTemplate');
        }
    };
    CodeBoard.prototype.removeFiles = function (filenames) {
        if (this._isFixedTemplate) {
            if (!Array.isArray(filenames)) {
                throw new Exceptions_1.ValidationError('array', 'The parameter is not array. please, check the api.');
            }
            this._board.removeFiles(filenames);
        }
        else {
            throw new Exceptions_1.ValidationError('opt', 'locked! because of isFixedTemplate');
        }
    };
    return CodeBoard;
}(MooBase_1.MooBase));
exports.CodeBoard = CodeBoard;
