import { getTemplate, integerSequence, VerdocsEndpoint } from "@verdocs/js-sdk";
import { Host, h, Fragment } from "@stencil/core";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
/**
 * Display a template preview experience. This will display the template's attached
 * documents with signing fields overlaid on each page. Fields will be color-coded
 * by recipient, and will be read-only (cannot be filled, moved, or altered).
 *
 * ```ts
 * <verdocs-preview
 *   templateId={TEMPLATE_ID}
 *   onSdkError={({ detail }) => { console.log('SDK error', detail) }
 *   />
 * ```
 */
export class VerdocsPreview {
    constructor() {
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The ID of the template to create the document from.
         */
        this.templateId = null;
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            this.template = template;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    onTemplateIdChanged(newTemplateId) {
        console.log('[PREVIEW] Template ID changed', newTemplateId);
        this.listenToTemplate();
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.endpoint.session) {
                console.log('[PREVIEW] Unable to start builder session, must be authenticated');
                return;
            }
            if (!this.templateId) {
                console.log(`[PREVIEW] Missing required template ID ${this.templateId}`);
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[PREVIEW] Error with preview session', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    handlePageRendered(_e) {
        // const pageInfo = e.detail as IDocumentPageInfo;
        // const fields = (this.template?.fields || []).filter(field => field.page === pageInfo.pageNumber);
        // console.log('[PREVIEW] Page rendered', pageInfo, fields);
        // fields.forEach(field => renderDocumentField(field, pageInfo, {disabled: true, editable: false, draggable: false}));
    }
    render() {
        var _a;
        if (this.loading) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        return (h(Host, null, (((_a = this.template) === null || _a === void 0 ? void 0 : _a.documents) || []).map(document => {
            const pageNumbers = integerSequence(1, document.pages);
            return (h(Fragment, null, pageNumbers.map(pageNumber => {
                var _a;
                const pageSize = ((_a = document.page_sizes) === null || _a === void 0 ? void 0 : _a[pageNumber]) || { width: 612, height: 792 };
                return (h("verdocs-template-document-page", { templateId: document.template_id, documentId: document.id, pageNumber: pageNumber, disabled: true, editable: false, done: false, virtualWidth: pageSize.width, virtualHeight: pageSize.height, onPageRendered: e => this.handlePageRendered(e), layers: [
                        { name: 'page', type: 'canvas' },
                        { name: 'controls', type: 'div' },
                    ] }));
            })));
        })));
    }
    static get is() { return "verdocs-preview"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-preview.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-preview.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "unknown",
                "attribute": "endpoint",
                "mutable": false,
                "complexType": {
                    "original": "VerdocsEndpoint",
                    "resolved": "VerdocsEndpoint",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "VerdocsEndpoint.getDefault()"
            },
            "templateId": {
                "type": "string",
                "attribute": "template-id",
                "mutable": false,
                "complexType": {
                    "original": "string | null",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the template to create the document from."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "null"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "sdkError",
                "name": "sdkError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired if an error occurs. The event details will contain information about the error. Most errors will\nterminate the process, and the calling application should correct the condition and re-render the component."
                },
                "complexType": {
                    "original": "SDKError",
                    "resolved": "SDKError",
                    "references": {
                        "SDKError": {
                            "location": "import",
                            "path": "../../../utils/errors",
                            "id": "src/utils/errors.ts::SDKError"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "templateId",
                "methodName": "onTemplateIdChanged"
            }];
    }
}
//# sourceMappingURL=verdocs-preview.js.map
