import { Host, h } from "@stencil/core";
import { Errors } from "../../services/errors";
import { Dialog } from "../../services/dialog";
import axios from "axios";
import { alertCodeByStatus } 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.appendData = {};
        this.appendHeaders = {};
        this.dialogInterval = undefined;
        this.withoutDialog = undefined;
        this.withoutSuccessDialog = undefined;
        this.withoutValidationDialog = undefined;
        this.response = undefined;
    }
    onSubmit(e) {
        var _a;
        e.preventDefault();
        Errors.setLoading(true);
        this.response = null;
        const data = new FormData(this.el.querySelector('form'));
        for (const key in this.appendData) {
            data.append(key, this.appendData[key]);
        }
        axios({
            method: this.method,
            url: this.action ? this.action : window.location.href,
            data: data,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'Content-Type': this.enctype, 'X-CSRF-TOKEN': (_a = document.querySelector('meta[name="csrf-token"]')) === null || _a === void 0 ? void 0 : _a.getAttribute('content') }),
        }).then((response) => {
            var _a;
            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));
    }
    catchError(err) {
        var _a;
        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, ((_a = err.response) === null || _a === void 0 ? void 0 : _a.data) || {});
            this.onFailed(err.response.data);
        }
        else {
            Dialog.exception({ message: err.message });
            this.onFailed(err.message);
        }
    }
    alertErrorByStatusCode(status, data) {
        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: (data === null || data === void 0 ? void 0 : data.message) || data,
                type: alertCodeByStatus(status),
                interval: this.dialogInterval,
            }).then((result) => {
                result === 'close' && this.onAction(data === null || data === void 0 ? void 0 : data.action);
            });
        }
    }
    onAction(action) {
        if (action === 'reload' || action === 'refresh') {
            Errors.setLoading(true);
            location.reload();
        }
        if (`${action}`.startsWith('redirect:')) {
            Errors.setLoading(true);
            location.href = `${action}`.replace('redirect:', '');
        }
    }
    onFailed(data) {
        this.failed.emit(data);
        Errors.setLoading(false);
    }
    onSuccess(data) {
        this.success.emit(data);
        Errors.setLoading(false);
        if (data === null || data === void 0 ? void 0 : data.action) {
            this.onAction(data.action);
        }
    }
    /**
     * Render the component
     */
    render() {
        return h(Host, { key: 'a27ee1ee26cf4c00374c6d761ee7fe07837c75b2' }, h("form", { key: '47afc21b30e77b2a538cbf8de9ab707e537470d1', "accept-charset": this.acceptCharset, autocomplete: this.autocomplete, enctype: this.enctype, method: this.method, action: this.action, onSubmit: (e) => this.onSubmit(e) }, h("slot", { key: '9f591f855ad9ec5e91d9f9323df7272895b97b39' })));
    }
    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": ""
                },
                "attribute": "action",
                "reflect": false
            },
            "acceptCharset": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "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": ""
                },
                "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": ""
                },
                "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": ""
                },
                "attribute": "enctype",
                "reflect": false,
                "defaultValue": "'application/x-www-form-urlencoded'"
            },
            "appendData": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "{}"
            },
            "appendHeaders": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "{}"
            },
            "dialogInterval": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "dialog-interval",
                "reflect": false
            },
            "withoutDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "without-dialog",
                "reflect": false
            },
            "withoutSuccessDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "without-success-dialog",
                "reflect": false
            },
            "withoutValidationDialog": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "without-validation-dialog",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "response": {}
        };
    }
    static get events() {
        return [{
                "method": "success",
                "name": "success",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "failed",
                "name": "failed",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
