"use strict";
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 Form_1 = require("../../Form");
const Modal_1 = require("../../Modal");
const autocomplete_1 = require("./autocomplete");
const PROCESS_STATUS_INIT_FORM = 'Ініціалізація пакету відправки';
const PROCESS_STATUS_SEND = 'Відправка пакету';
const ERROR_URL_INIT = 'Сталась помилка при ініціалізації форми';
const ERROR_URL_SEND = 'Сталась помилка при відправці пакету';
class EndpointModal extends Modal_1.ProcessModal {
    static create(props) {
        return new EndpointModal(props);
    }
    constructor(props) {
        super({
            title: 'Відправка до митниці',
            actionText: 'Відправити',
            actionCallback: () => this._handleActionClick()
        });
        this.source = [];
        this.props = props;
        this._makeModal();
        this._makeHandle();
    }
    _makeModal() {
        this.modalBodyForm.append('<div class="form-group row mb-2"><label class="col-form-label col-sm-4 text-right"><span class="text-bold text-danger">*</span> Email відправника</label><div class="col-sm-8"><input type="email" name="p_sender_email" class="form-control" required maxlength="128"></div></div>' +
            '<div class="form-group row mb-2"><label class="col-form-label col-sm-4 text-right"><span class="text-bold text-danger">*</span> ПІБ відправника</label><div class="col-sm-8"><input type="text" name="p_sender_name" class="form-control" required maxlength="200"></div></div>' +
            '<div class="form-group row mb-2"><label class="col-form-label col-sm-4 text-right">Код підрозділу митного оформлення</label><div class="col-sm-8"><input type="text" name="p_recipient" class="form-control" required /></div></div>');
    }
    _makeHandle() {
        const form = this.modalBodyForm;
        form.find('[name=p_recipient]').on('selection', (event) => console.log('AutoComplete.selection', event.detail));
        const input = form.find('[name=p_recipient]').get(0);
        const config = {
            selector: () => input,
            placeHolder: 'Кінцева точка',
            resultItem: {
                highlight: true
            },
            events: {
                input: {
                    focus: () => {
                        this.recipientInput.start();
                    },
                    selection: (event) => {
                        const selection = event.detail.selection.value.id;
                        this.recipientInput.input.value = selection;
                    }
                }
            }
        };
        if (this.props.urlEndpointList) {
            this.recipientInput = new autocomplete_1.AutoComplete(Object.assign(Object.assign({}, config), { data: {
                    src: () => __awaiter(this, void 0, void 0, function* () {
                        try {
                            // Loading placeholder text
                            input.setAttribute('placeholder', 'Завантаження...');
                            // Fetch External Data Source
                            const source = yield fetch(new URL(this.props.urlEndpointList || ''));
                            const data = yield source.json();
                            // Post Loading placeholder text
                            input.setAttribute('placeholder', 'Кінцева точка');
                            // Returns Fetched data
                            return data;
                        }
                        catch (error) {
                            return error;
                        }
                    }),
                    keys: ['text']
                } }));
        }
        else {
            this.recipientInput = new autocomplete_1.AutoComplete(Object.assign(Object.assign({}, config), { data: {
                    src: () => this.source,
                    keys: ['text']
                }, threshold: 0 }));
        }
        (0, Form_1.Validator)(form);
    }
    _handleActionClick() {
        const form = this.modalBodyForm;
        if ((0, Form_1.Validator)(form).form()) {
            this.showLoader(PROCESS_STATUS_SEND);
            Form_1.$.ajax({
                url: this.props.urlSave,
                data: form.serialize()
            })
                .done((data) => {
                if (data && data.ok) {
                    this.modal.close();
                    this.props.onSuccess && this.props.onSuccess();
                }
                else {
                    this.hideLoader();
                    this.setError(ERROR_URL_SEND, data.msg);
                }
            })
                .fail(() => {
                this.hideLoader();
                this.setError(ERROR_URL_SEND);
            });
        }
    }
    _clearForm() {
        if (this.props.urlInit) {
            this.showLoader(PROCESS_STATUS_INIT_FORM);
            Form_1.$.ajax({
                url: this.props.urlInit
            })
                .always(() => this.hideLoader())
                .done((data) => {
                if (data && data.ok) {
                    const form = this.modalBodyForm;
                    form.find('[name=p_sender_email]').val(data.user.email).trigger('change');
                    form.find('[name=p_sender_name]').val(data.user.fio).trigger('change');
                    if (data.endpoint.length == 1) {
                        this.recipientInput.input.value = data.endpoint[0].id;
                    }
                    else {
                        this.source = data.endpoint;
                    }
                    /* form.find('[name=p_recipient]')
                        .html(data.endpoint.map((item: { id: string; text: string; html: string }) => `<option value='${item.id}' data-html='${encodeURIComponent(item.html)}'>${item.text}</option>`).join(''))
                        .trigger('change'); */
                }
                else {
                    this.setError(ERROR_URL_INIT);
                }
            })
                .fail(() => this.setError(ERROR_URL_INIT));
        }
    }
    open() {
        super.openModal();
        this._clearForm();
    }
}
exports.default = EndpointModal;
