"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const Modal_1 = __importStar(require("../../Modal"));
// @ts-ignore
const jquery_fancytree_1 = require("jquery.fancytree");
const recaptcha_v3_1 = require("recaptcha-v3");
const errorText = 'Помилка на сайті';
const defaultProps = {
    title: 'УКТЗЕД 2020'
};
class ChoiceUktved {
    static create(props) {
        return new ChoiceUktved(Object.assign(Object.assign({}, defaultProps), props));
    }
    constructor(props) {
        this.props = props;
        this.state = {
            target: null,
            container: document.createElement('div'),
            buttons: document.createElement('div'),
            tree: null,
            activeCode: null,
            recaptcha: null
        };
        this.initTree();
        this.initButtons();
        //if (props.withReCaptcha) {
        (0, recaptcha_v3_1.load)('6Ld2gbgZAAAAAMFijtWxOp5WN_cgviTzpZi7YzMy').then(recaptcha => this.state.recaptcha = recaptcha);
        //}
    }
    initTree() {
        this.state.container.id = 'FinderUktved';
        this.state.container.classList.add('pre-scrollable');
        document.body.append(this.state.container);
        this.state.tree = (0, jquery_fancytree_1.createTree)('#FinderUktved', {
            strings: {
                loading: 'Завантаження...',
                loadError: 'Помилка завантаження!',
                moreData: 'Більше...',
                noData: 'Немає даних.'
            },
            source: {
                url: '/ua/core.api.uktved',
                cache: true
            },
            lazyLoad: (event, data) => {
                const key = data.node.key;
                data.node.setStatus('loading');
                data.result = new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
                    let url = `/ua/core.api.uktved?p_mode=children&p_parent=${key}`;
                    if (this.state.recaptcha) {
                        const token = yield this.state.recaptcha.execute('core_ukrved');
                        url += `&p_recaptcha=${token}`;
                    }
                    const response = yield fetch(url);
                    const blob = yield response.blob();
                    const reader = new FileReader();
                    reader.readAsText(blob, 'windows-1251');
                    reader.onload = function () {
                        resolve(JSON.parse(reader.result));
                    };
                }));
                /*data.result = {
                    url: '/ua/core.api.uktved',
                    data: { p_mode: 'children', p_parent: node.key, p_recaptcha: token },
                    cache: true
                };*/
            },
            postProcess: (event, data) => {
                if (!data.response.ok) {
                    data.result = { error: data.response.msg || 'Didn\'t work :-/' };
                }
                else {
                    data.result = data.response.result;
                }
            },
            renderTitle: (_event, data) => {
                return `<span class='fancytree-title text-wrap' style='width: calc(100% - 3.7rem);'>${data.node.title}</span>`;
            },
            beforeActivate: (_event, data) => {
                var _a;
                return (_a = data.node.data.canSelect) !== null && _a !== void 0 ? _a : true;
            },
            dblclick: (_event, data) => {
                var _a;
                const canSelect = (_a = data.node.data.canSelect) !== null && _a !== void 0 ? _a : true;
                if (canSelect && !data.node.folder) {
                    this.handleSelectItem(data.node);
                    this.handleSubmit();
                }
            },
            activate: (_event, data) => {
                this.handleSelectItem(data.node);
            }
        });
    }
    initButtons() {
        this.state.buttons.innerHTML += (`<button type='button' class='btn btn-primary'>Обрати</button>`);
        this.state.buttons.innerHTML += (`<button type='button' class='btn btn-light ml-2' data-bs-dismiss='modal'>Закрити</button>`);
        const actionBtn = this.state.buttons.querySelector('.btn-primary');
        actionBtn.disabled = true;
        actionBtn.addEventListener('click', () => this.handleSubmit());
    }
    handleSelectItem(node) {
        this.state.buttons.querySelector('.btn-primary').disabled = false;
        this.state.activeCode = node.data.code;
    }
    handleSubmit() {
        if (this.state.target && typeof this.state.activeCode === 'string') {
            this.state.target.value = this.state.activeCode;
        }
        Modal_1.default.close();
    }
    open(form) {
        this.state.target = form.target;
        Modal_1.default.open(this.props.title, Modal_1.ModalSize.full);
        Modal_1.default.setBody(this.state.container);
        Modal_1.default.setFooter(this.state.buttons);
        Modal_1.default.onClose(() => {
            (0, recaptcha_v3_1.getInstance)().hideBadge();
        });
    }
}
exports.default = ChoiceUktved;
