import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { E as Errors } from './errors.js';
import { D as Dialog } from './dialog.js';
import { a as axios } from './axios.js';
import { m as toSnakeCase, k as getMeta, b as alertCodeByStatus } from './helpers.js';

const styleCss = "x-form{display:block;text-align:inherit}x-form-row{position:relative;text-align:inherit;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-0.6rem;margin-left:-0.6rem}x-form-row>.col,x-form-row>[class*=col-]{padding-right:0.6rem;padding-left:0.6rem}x-form-row+hr{margin-top:0.25rem !important}x-form-group{display:block;text-align:inherit;position:relative;margin-bottom:1.2rem}fieldset{margin:0px;padding:0px;border:none;margin-bottom:1rem}fieldset .fieldset-item{margin-bottom:1rem}fieldset .fieldset-item:last-child{margin-bottom:0px}";
const XFormStyle0 = styleCss;

const XForm$1 = /*@__PURE__*/ proxyCustomElement(class XForm extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.success = createEvent(this, "success", 3);
        this.failed = createEvent(this, "failed", 3);
        this.action = undefined;
        this.acceptCharset = 'UTF-8';
        this.method = 'POST';
        this.autocomplete = 'on';
        this.enctype = 'application/x-www-form-urlencoded';
        this.timeout = 30000;
        this.appendData = {};
        this.appendHeaders = {};
        this.dialogInterval = undefined;
        this.withoutDialog = undefined;
        this.withoutSuccessDialog = undefined;
        this.withoutValidationDialog = undefined;
        this.response = undefined;
        this.submitter = undefined;
    }
    /**
     * Submit event handler
     */
    onSubmit(e) {
        var _a;
        e.preventDefault();
        this.submitter = (_a = e.submitter) === null || _a === void 0 ? void 0 : _a.closest('x-button');
        Errors.setLoading(true);
        this.form.dispatchEvent(new CustomEvent('loading', { bubbles: false, detail: true }));
        this.response = null;
        const data = new FormData(this.form);
        for (const key in this.appendData) {
            data.append(key, this.appendData[key]);
        }
        for (const key in this.form.dataset) {
            data.append(toSnakeCase(key), this.form.dataset[key]);
        }
        if (this.submitter) {
            this.submitter.loading = true;
            this.submitter.disabled = true;
        }
        axios({
            method: this.method,
            url: this.action ? this.action : window.location.href,
            data: data,
            timeout: this.timeout,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'Content-Type': this.enctype, 'X-CSRF-TOKEN': getMeta('csrf-token') }),
        }).then((response) => {
            var _a;
            if (this.submitter) {
                this.submitter.loading = false;
                this.submitter.disabled = false;
            }
            this.response = response;
            if (this.withoutDialog || this.withoutSuccessDialog) {
                this.onSuccess(response.data);
            }
            else {
                Dialog.success({
                    message: (_a = response.data) === null || _a === void 0 ? void 0 : _a.message,
                    interval: this.dialogInterval,
                }).then((result) => {
                    result === 'close' && this.onSuccess(response.data);
                });
            }
        }).catch(this.catchError.bind(this));
    }
    /**
     * Catch error
     */
    catchError(err) {
        var _a, _b;
        if (this.submitter) {
            this.submitter.loading = false;
            this.submitter.disabled = false;
        }
        if (err === null || err === void 0 ? void 0 : err.response) {
            this.response = (err === null || err === void 0 ? void 0 : err.response) || null;
            this.alertErrorByStatusCode(err.status, (_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {});
            this.onFailed(err.response.data);
        }
        else {
            Dialog.exception({ message: err.message });
            this.onFailed(err.message);
        }
    }
    /**
     * Alert error by status code
     */
    alertErrorByStatusCode(status, data) {
        var _a;
        const hasValidationErrors = data === null || data === void 0 ? void 0 : data.errors;
        if (hasValidationErrors) {
            Errors.fill(data.errors);
        }
        if (this.withoutDialog || (this.withoutValidationDialog && hasValidationErrors)) {
            this.onAction(data === null || data === void 0 ? void 0 : data.action);
        }
        else {
            Dialog({
                message: (_a = data === null || data === void 0 ? void 0 : data.message) !== null && _a !== void 0 ? _a : data,
                type: alertCodeByStatus(status),
                interval: this.dialogInterval,
            }).then((result) => {
                result === 'close' && this.onAction(data === null || data === void 0 ? void 0 : data.action);
            });
        }
    }
    /**
     * On action
     */
    onAction(action) {
        if (action === 'reload' || action === 'refresh') {
            Errors.setLoading(true);
            this.form.dispatchEvent(new CustomEvent('loading', { bubbles: false, detail: true }));
            location.reload();
        }
        if (`${action}`.startsWith('redirect:')) {
            Errors.setLoading(true);
            this.form.dispatchEvent(new CustomEvent('loading', { bubbles: false, detail: true }));
            location.href = `${action}`.replace('redirect:', '');
        }
    }
    /**
     * On failed
     */
    onFailed(data) {
        this.failed.emit(data);
        this.form.dispatchEvent(new CustomEvent('failed', { bubbles: false, detail: data }));
        Errors.setLoading(false);
        this.form.dispatchEvent(new CustomEvent('loading', { bubbles: false, detail: false }));
    }
    /**
     * On success
     */
    onSuccess(data) {
        this.success.emit(data);
        this.form.dispatchEvent(new CustomEvent('success', { bubbles: false, detail: data }));
        Errors.setLoading(false);
        this.form.dispatchEvent(new CustomEvent('loading', { bubbles: false, detail: false }));
        if (data === null || data === void 0 ? void 0 : data.action) {
            this.onAction(data.action);
        }
    }
    /**
     * Render the component
     */
    render() {
        return h(Host, { key: '79508a00b16e7080302194f63b817015dc180441' }, h("form", { key: 'b98d1fca971f2870d900e4e83e226b57c4215589', ref: el => this.form = el, "accept-charset": this.acceptCharset, autocomplete: this.autocomplete, enctype: this.enctype, method: this.method, action: this.action, onSubmit: (e) => this.onSubmit(e) }, h("slot", { key: '577434c8f754a929ad0fc3cd0929fa3587c818db' })));
    }
    get el() { return this; }
    static get style() { return XFormStyle0; }
}, [4, "x-form", {
        "action": [1],
        "acceptCharset": [1, "accept-charset"],
        "method": [1],
        "autocomplete": [1],
        "enctype": [1],
        "timeout": [2],
        "appendData": [16],
        "appendHeaders": [16],
        "dialogInterval": [2, "dialog-interval"],
        "withoutDialog": [4, "without-dialog"],
        "withoutSuccessDialog": [4, "without-success-dialog"],
        "withoutValidationDialog": [4, "without-validation-dialog"],
        "response": [32],
        "submitter": [32]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["x-form"];
    components.forEach(tagName => { switch (tagName) {
        case "x-form":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, XForm$1);
            }
            break;
    } });
}

const XForm = XForm$1;
const defineCustomElement = defineCustomElement$1;

export { XForm, defineCustomElement };
