/*
 * @package    ECLCDEK shipping plugin СДЭК to RadicalMart
 * @subpackage    ECLCDEK
 * @version    1.0.1
 * @author Econsult Lab.
 * @copyright  Copyright (c) 2025 Econsult Lab. All rights reserved.
 * @license    GNU/GPL license: https://www.gnu.org/copyleft/gpl.html
 * @link       https://econsultlab.ru
 */

/**
 * Базовый класс редактирования настроек способов доставки пользователя во фронте
 * @since 1.0.0
 */
class ECLCDEKFrontPersonal extends ECLCDEK {
    /**
     * Параметры инициализации
     * @type {object}
     * @since 1.0.0
     */
    #params;

    constructor(params) {
        const _defaultParams = {
            common: {
                core: {
                    debug: true,
                    ajaxLoader: null,
                    disabled_class: "uk-disabled",
                },
                city_field_id: "jform_shipping_city",
                country_field_id: "jform_shipping_country",
                region_field_id: "jform_shipping_region",
                calculationParams: {},
                task: "personal",
                client: "site",
                deliveryType: "office",
                result: "",
                widgetParams: null,
                parent_selector: {
                    name: 'aria-controls',
                    value: ''
                }
            }
        }
        params ??= _defaultParams;
        // Инициализация спинера
        let _container = document.getElementById("personalForm");
        let _loader = null;
        if(_container) {
            _loader = document.getElementById("personal_shipping_loading");
            if(!_loader) {
                _loader = document.createElement('div');
                _loader.setAttribute("id", "personal_shipping_loading");
                _loader.classList.add("uk-position-cover","uk-flex","uk-flex-center","uk-flex-middle","uk-overlay-default","uk-position-z-index");
                _loader.style = "none";
                let _spinner = document.createElement("div");
                _spinner.setAttribute("uk-spinner", "ratio: 3");
                _loader.appendChild(_spinner);
                _container.appendChild(_loader);
            }
        }
        params.common.core.ajaxLoader = _loader;
        super(params.common);
        this.#params = params;
        this.className = "ECLCDEKFrontPersonal-"+params.common.parent_selector.value;
        this.debug('constructor', "this.#params", this.#params);

        let _addr = "";
        let _msg = {
            type: "",
            text: "",
            formatted: ""
        };
        try {
            _addr = JSON.parse(this.results_block.result_input.value);
        } catch (err) {
            _addr = "";
        }

        this.debug('constructor', "_addr", _addr);

        let _check = Object.keys(_addr).length === 0 || !_addr.address;
        if (_check) {
            _msg = {
                type: "warning",
                text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_SETTINGS_MESSAGE_NEED_TO_" + (this.#params.common.deliveryType === "office" ? "PVZ" : "ADDRESS")),
                formatted: ""
            };
            this.initializeMap();
        }
        let _result = this.getBaseResult();
        _result.disabled_btns.map_btn = !_check;
        _result.disabled_btns.reset_btn = _check;
        _result.output_params.result = _addr;
        _result.message = _msg;

        this.current_results = _result;
        this.successCallBack = this.updateResult;
        this.errorCallBack = this.showError;
        this.getResultFormatted(_result);
    }

    /**
     * Инициализирует блок результата выбора адреса
     *
     * @since 1.0.0
     */
    initializeResultsBlock() {
        this.debug('initializeResultsBlock', "started", '...');
        this.debug('initializeResultsBlock', "this.params.parent_selector", this.params.parent_selector);
        if (typeof this.params.parent_selector !== "undefined" && this.params.parent_selector.name && this.params.parent_selector.value) {
            const _container = document.querySelector('*[' + this.params.parent_selector.name + '=' + this.params.parent_selector.value + '] #' + this.params.result);
            this.debug('initializeResultsBlock', "_container", _container);
            if (_container) {
                this.results_block.result_input = _container.querySelector("input[type='hidden']");
                this.results_block.message_container = _container.querySelector('div');
                this.results_block.show_map_btn = _container.querySelector('#cdek-btn');
                this.results_block.show_map_btn.text = Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_CHOOSE_" + this.params.deliveryType.toUpperCase() + "_DELIVERY");
                this.results_block.reset_btn = _container.querySelector('#cdek-btn-reset');
                _container.addEventListener('change', event => this.onChangeTariff(event.target, this))
            }
        }
        this.debug('initializeResultsBlock', "this.results_block", this.results_block);
        this.debug('initializeResultsBlock', "done", '...');
    }

    /**
     * Предварительная обработка адреса
     *
     * @param {object} address  Адрес
     *
     * @returns {Result}
     *
     * @since 1.0.0
     */
    preProcessAddress(address) {
        let _result = super.preProcessAddress(address);
        _result.client = this.#params.common.client;
        _result.task = this.#params.common.task;
        return _result;
    }

    /**
     * @inheritDoc
     *
     * @returns {Result}
     *
     * @since 1.0.0
     */
    getBaseResult() {
        return super.getBaseResult();
    }

    /**
     * @inheritDoc
     *
     * @since 1.0.0
     */
    onReadyMap(_this) {
        super.onReadyMap(_this);
        let _result = this.getBaseResult();
        _result.disabled_btns = {
            map_btn: false,
            reset_btn: true,
        };
        _result.message = {
            type: "primary",
            text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_CUSTOMER_MESSAGE_READY_CHOOSE_" + _this.#params.common.deliveryType + "_TEXT"),
            formatted: ""
        };
        this.successCallBack = this.updateResult;
        this.errorCallBack = this.showError;
        this.getResultFormatted(_result);
    }
}