// NOTE: This component does not have a story because it's not intended for external use.
import { getTemplate, getTemplateDocumentPageDisplayUri, VerdocsEndpoint } from "@verdocs/js-sdk";
import { h, Host, Fragment } from "@stencil/core";
import { getControlStyles, getFieldId } from "../../../utils/utils";
import { throttle } from "../../../utils/utils";
import { Store } from "../../../utils/Datastore";
/**
 * Represents one document page. This is primarily a layout container used to coordinate positions of
 * page-related layers such as the page itself, signature fields, etc. It is not intended to be used
 * on its own as an individual component.
 */
export class VerdocsTemplateDocumentPage {
    constructor() {
        this.templateListenerId = null;
        /**
         * The endpoint to load from.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * Whether the fields should be editable (Builder)
         */
        this.editable = false;
        /**
         * Whether the fields should be disabled (Builder)
         */
        this.disabled = false;
        /**
         * Whether the field are interactable (done/submitted disables this)
         */
        this.done = false;
        /**
         * The ID of the template the document is for.
         */
        this.templateId = '';
        /**
         * The ID of the document to display.
         */
        this.documentId = '';
        /**
         * The page number being rendered. (Reminder: page numbers are 1-based.)
         */
        this.pageNumber = 1;
        /**
         * The "virtual" width of the page canvas. Defaults to 612 which at 72dpi is 8.5" wide. This is used to compute
         * the aspect ratio of the final rendered element when scaling up/down.
         */
        this.virtualWidth = 612;
        /**
         * The "virtual" height of the page canvas.  Defaults to 792 which at 72dpi is 11" tall. This is used to compute
         * the aspect ratio of the final rendered element when scaling up/down.
         */
        this.virtualHeight = 792;
        /**
         * The layers that will be rendered. The DOM structure will be a DIV container with one child DIV for each layer.
         * The parent DIV will have a unique ID, and each child DIV will have that ID with the layer name appended, e.g.
         * if `pages` was ['page', 'fields'] the structure will be:
         *
         * ```
         *     <div id="verdocs-document-page-ker2fr1p9">
         *       <div id="verdocs-document-page-ker2fr1p9-page"></div>
         *       <div id="verdocs-document-page-ker2fr1p9-fields"></div>
         *     </div>
         * ```
         */
        this.layers = [{ name: 'page', type: 'canvas' }];
        this.containerId = `verdocs-document-page-${Math.random().toString(36).substring(2, 11)}`;
        this.renderedWidth = this.virtualWidth;
        this.renderedHeight = this.virtualHeight;
        this.naturalWidth = this.virtualWidth;
        this.naturalHeight = this.virtualHeight;
        this.aspectRatio = this.virtualWidth / this.virtualHeight;
        this.skipFirstNotification = true;
        this.pageDisplayUri = '';
        this.xScale = 1;
        this.yScale = 1;
        this.loading = true;
        this.template = null;
    }
    async componentWillLoad() {
        this.pageDisplayUri = await getTemplateDocumentPageDisplayUri(this.endpoint, this.documentId, this.pageNumber);
        this.listenToTemplate();
    }
    componentDidLoad() {
        this.resizeObserver = new ResizeObserver(throttle(entries => {
            for (const entry of entries) {
                const renderedWidth = entry.contentRect.width;
                this.renderedWidth = renderedWidth;
                this.renderedHeight = this.virtualHeight * (renderedWidth / this.virtualWidth);
            }
            this.notifyRenderedSize();
        }, 100));
        this.resizeObserver.observe(this.container);
    }
    componentDidUpdate() {
        // This is fired when fields are updated and triggers the parent to re-attach behaviors like drag-and-drop
        this.notifyRenderedSize();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
        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;
        }
    }
    notifyRenderedSize() {
        // We skip one notification because by default we will always get at least two, one when rendering the initial size
        // and a second once we're able to compute the scale size, when the resizeObserver sets renderedWidth/renderedHeight.
        if (this.skipFirstNotification) {
            this.skipFirstNotification = false;
            return;
        }
        const xScale = this.renderedWidth / this.virtualWidth;
        if (this.xScale !== xScale) {
            this.xScale = xScale;
        }
        const yScale = this.renderedHeight / this.virtualHeight;
        if (this.yScale !== yScale) {
            this.yScale = yScale;
        }
        this.pageRendered.emit({
            // container: this.container,
            containerId: this.containerId,
            documentId: this.documentId,
            pageNumber: this.pageNumber,
            virtualWidth: this.virtualWidth,
            virtualHeight: this.virtualHeight,
            renderedWidth: this.renderedWidth,
            renderedHeight: this.renderedHeight,
            naturalWidth: this.naturalWidth,
            naturalHeight: this.naturalHeight,
            aspectRatio: this.aspectRatio,
            xScale,
            yScale,
        });
    }
    render() {
        if (this.loading) {
            return (h(Host, null, h("img", { src: "https://public-assets.verdocs.com/loading-placeholder.png", class: "placeholder", alt: "Placeholder page" })));
        }
        const height = `${this.renderedHeight}px`;
        return (h(Host, { id: `${this.containerId}`, style: { height, flex: `0 0 ${height}` } }, this.layers.map(layer => {
            var _a;
            return layer.type === 'div' ? (h("div", { class: "verdocs-template-document-page-layer", id: `${this.containerId}-${layer.name}`, style: { height } }, layer.name === 'controls' &&
                (((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || [])
                    .filter(field => field && field.page === this.pageNumber)
                    .map(field => {
                    var _a, _b;
                    const id = getFieldId(field);
                    let { name, type, multiline } = field;
                    const { xScale, yScale, templateId, editable, disabled, done, pageNumber } = this;
                    if (((_a = field['setting']) === null || _a === void 0 ? void 0 : _a.leading) > 0 || ((_b = field['settings']) === null || _b === void 0 ? void 0 : _b.leading) > 0) {
                        type = 'textarea';
                        multiline = true;
                    }
                    switch (type) {
                        case 'textbox':
                            return (h("verdocs-field-textbox", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, multiline: multiline, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'textarea':
                            return (h("verdocs-field-textarea", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'date':
                            return (h("verdocs-field-date", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'attachment':
                            return (h("verdocs-field-attachment", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'dropdown':
                            return (h("verdocs-field-dropdown", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'initial':
                            return (h("verdocs-field-initial", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'signature':
                            return (h("verdocs-field-signature", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, this.xScale, this.yScale) }));
                        case 'timestamp':
                            return (h("verdocs-field-timestamp", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'checkbox':
                            return (h("verdocs-field-checkbox", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        case 'radio':
                            return (h("verdocs-field-radio", { id: id, fieldname: name, source: "template", sourceid: templateId, editable: editable, disabled: disabled, done: done, xscale: xScale, yscale: yScale, pagenumber: pageNumber, style: getControlStyles(field, xScale, yScale) }));
                        default:
                            return h(Fragment, null, name);
                    }
                }))) : this.pageDisplayUri ? (h("img", { class: "verdocs-template-document-page-layer img", id: `${this.containerId}-${layer.name}`, src: this.pageDisplayUri, alt: `Page ${this.pageNumber}`, "aria-hidden": true, loading: "lazy", onLoad: (e) => {
                    // Note that all we really care about is the aspect ratio. We track the natural Width and Height but they aren't really that
                    // useful as individual values. The image will already have been scaled down to fit a DIV for display (100%, auto height).
                    // Builder places fields offset into the rendered display area, not the original document's dimensions. So its X/Y values
                    // for a field are based on the responsive Web view the Template editor was seeing. The IMG was scaled down there in the
                    // exact same way, so we just honor it. We capture the natural width and height here more as information. Then we use the
                    // aspect ratio to adjust the "virtual" height in case the page is not 8.5"x11".
                    // TODO: Store this in the DB with each page.
                    this.naturalWidth = e.target.naturalWidth;
                    this.naturalHeight = e.target.naturalHeight;
                    this.aspectRatio = this.naturalWidth / this.naturalHeight;
                    this.virtualHeight = this.virtualWidth / this.aspectRatio;
                    this.renderedHeight = e.target.offsetWidth / this.aspectRatio;
                } })) : (h("div", null));
        })));
    }
    static get is() { return "verdocs-template-document-page"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-document-page.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-document-page.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 load from."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "VerdocsEndpoint.getDefault()"
            },
            "editable": {
                "type": "boolean",
                "attribute": "editable",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether the fields should be editable (Builder)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "disabled": {
                "type": "boolean",
                "attribute": "disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether the fields should be disabled (Builder)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "done": {
                "type": "boolean",
                "attribute": "done",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether the field are interactable (done/submitted disables this)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "templateId": {
                "type": "string",
                "attribute": "template-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the template the document is for."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "documentId": {
                "type": "string",
                "attribute": "document-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the document to display."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "pageNumber": {
                "type": "number",
                "attribute": "page-number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The page number being rendered. (Reminder: page numbers are 1-based.)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "1"
            },
            "virtualWidth": {
                "type": "number",
                "attribute": "virtual-width",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The \"virtual\" width of the page canvas. Defaults to 612 which at 72dpi is 8.5\" wide. This is used to compute\nthe aspect ratio of the final rendered element when scaling up/down."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "612"
            },
            "virtualHeight": {
                "type": "number",
                "attribute": "virtual-height",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The \"virtual\" height of the page canvas.  Defaults to 792 which at 72dpi is 11\" tall. This is used to compute\nthe aspect ratio of the final rendered element when scaling up/down."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "792"
            },
            "layers": {
                "type": "unknown",
                "attribute": "layers",
                "mutable": false,
                "complexType": {
                    "original": "IPageLayer[]",
                    "resolved": "IPageLayer[]",
                    "references": {
                        "IPageLayer": {
                            "location": "import",
                            "path": "../../../utils/Types",
                            "id": "src/utils/Types.ts::IPageLayer"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The layers that will be rendered. The DOM structure will be a DIV container with one child DIV for each layer.\nThe parent DIV will have a unique ID, and each child DIV will have that ID with the layer name appended, e.g.\nif `pages` was ['page', 'fields'] the structure will be:\n\n```\n    <div id=\"verdocs-document-page-ker2fr1p9\">\n      <div id=\"verdocs-document-page-ker2fr1p9-page\"></div>\n      <div id=\"verdocs-document-page-ker2fr1p9-fields\"></div>\n    </div>\n```"
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[{name: 'page', type: 'canvas'}]"
            }
        };
    }
    static get states() {
        return {
            "containerId": {},
            "renderedWidth": {},
            "renderedHeight": {},
            "naturalWidth": {},
            "naturalHeight": {},
            "aspectRatio": {},
            "skipFirstNotification": {},
            "pageDisplayUri": {},
            "xScale": {},
            "yScale": {},
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "pageRendered",
                "name": "pageRendered",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Fired when a page has been rendered. This is also fired when the page is resized."
                },
                "complexType": {
                    "original": "IDocumentPageInfo",
                    "resolved": "IDocumentPageInfo",
                    "references": {
                        "IDocumentPageInfo": {
                            "location": "import",
                            "path": "../../../utils/Types",
                            "id": "src/utils/Types.ts::IDocumentPageInfo"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "container"; }
}
//# sourceMappingURL=verdocs-template-document-page.js.map
