import { Host, h } from "@stencil/core";
import { Errors } from "../../services/errors";
import { Dialog } from "../../services/dialog";
import axios from "axios";
import { alertCodeByStatus, toSnakeCase } from "../../utils/helpers";
export class XForm {
    constructor() {
        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, _b;
        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': (_b = document.querySelector('meta[name="csrf-token"]')) === null || _b === void 0 ? void 0 : _b.getAttribute('content') }),
        }).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: '9d19010a9a8039eac2fce4e042c64385ddbbec4d' }, h("form", { key: 'ee688ad58a586b752f83834fcf5921fea3e8da93', 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: '9ca54015772b2edb4e9a7fba7b1e5cdd41be57a5' })));
    }
    static get is() { return "x-form"; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "action": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element action URL"
                },
                "attribute": "action",
                "reflect": false
            },
            "acceptCharset": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element charset option"
                },
                "attribute": "accept-charset",
                "reflect": false,
                "defaultValue": "'UTF-8'"
            },
            "method": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormMethodType",
                    "resolved": "\"GET\" | \"POST\"",
                    "references": {
                        "FormMethodType": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-form/component.tsx",
                            "id": "src/components/x-form/component.tsx::FormMethodType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element form method (GET ans POST only)"
                },
                "attribute": "method",
                "reflect": false,
                "defaultValue": "'POST'"
            },
            "autocomplete": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormAutocompleteType",
                    "resolved": "\"off\" | \"on\"",
                    "references": {
                        "FormAutocompleteType": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-form/component.tsx",
                            "id": "src/components/x-form/component.tsx::FormAutocompleteType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element autocomplete option"
                },
                "attribute": "autocomplete",
                "reflect": false,
                "defaultValue": "'on'"
            },
            "enctype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormEnctypeType",
                    "resolved": "\"application/json\" | \"application/x-www-form-urlencoded\" | \"multipart/form-data\" | \"text/plain\"",
                    "references": {
                        "FormEnctypeType": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-form/component.tsx",
                            "id": "src/components/x-form/component.tsx::FormEnctypeType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element enctype option"
                },
                "attribute": "enctype",
                "reflect": false,
                "defaultValue": "'application/x-www-form-urlencoded'"
            },
            "timeout": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element request timeout"
                },
                "attribute": "timeout",
                "reflect": false,
                "defaultValue": "30000"
            },
            "appendData": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element append data"
                },
                "defaultValue": "{}"
            },
            "appendHeaders": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element append headers"
                },
                "defaultValue": "{}"
            },
            "dialogInterval": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element dialog interval"
                },
                "attribute": "dialog-interval",
                "reflect": false
            },
            "withoutDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element without dialog on submit"
                },
                "attribute": "without-dialog",
                "reflect": false
            },
            "withoutSuccessDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element without dialog on success response"
                },
                "attribute": "without-success-dialog",
                "reflect": false
            },
            "withoutValidationDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element without dialog on validation error"
                },
                "attribute": "without-validation-dialog",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "response": {},
            "submitter": {}
        };
    }
    static get events() {
        return [{
                "method": "success",
                "name": "success",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Submit event"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "failed",
                "name": "failed",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
