/*
 * @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 ECLCDEKAdminCustomer extends ECLCDEK {

    /**
     * Параметры инициализации
     * @type {object}
     * @since 1.0.0
     */
    #params;

    constructor(params) {
        const _defaultParams = {
            common: {
                core: {
                    debug: true,
                    ajaxLoader: null,
                    disabled_class: "pe-none",
                },
                city_field_id: "jform_params_from_city",
                country_field_id: "jform_params_from_country",
                region_field_id: "jform_params_from_region",
                calculationParams: {},
                task: "customer",
                client: "admin",
                deliveryType: "office",
                result: "",
                widgetParams: null,
                parent_selector: {
                    name: 'aria-controls',
                    value: ''
                }
            },

        }
        params ??= _defaultParams;

        let _loader = document.body.getElementsByTagName('joomla-core-loader');
        if (_loader.length === 0) {
            _loader = document.body.appendChild(document.createElement('joomla-core-loader'));
            params.common.core.ajaxLoader = _loader;
        } else {
            params.common.core.ajaxLoader = _loader[0];
        }

        super(params.common);
        this.#params = params;
        this.className = "ECLCDEKAdminCustomer-"+params.common.parent_selector.value;
        this.debug('constructor', "params", 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", '...');
    }

    /**
     * @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);
    }

    /**
     * Предварительная обработка адреса
     *
     * @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();
    }
}