'use strict';

var index = require('./index-DLmnUl1_.js');
var jsSdk = require('@verdocs/js-sdk');
var Toast = require('./Toast-BgG-6jAg.js');
var errors = require('./errors-D1XRvnet.js');
var Datastore = require('./Datastore-C-Pojt3E.js');

const verdocsTemplateSettingsCss = () => `verdocs-template-settings{display:block;max-width:600px;font-family:var(--verdocs-primary-font, "Inter", "Barlow", sans-serif)}verdocs-template-settings>form{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;background-color:#ffffff;padding:12px}verdocs-template-settings>form h5{font-size:16px;font-weight:bold;color:#46497d;margin:0 0 10px 0}verdocs-template-settings>form label{display:block;font-size:14px;font-weight:500;margin:0 0 4px 0;color:#5c6575}verdocs-template-settings>form input{border:none;font-size:18px;padding:3px 6px 3px 0;background:transparent;border-bottom:1px solid #33364b}verdocs-template-settings>form input:focus{outline:none}verdocs-template-settings>form .row{margin:20px 0 0 0}verdocs-template-settings .buttons{display:-ms-flexbox;display:flex;-webkit-column-gap:8px;-moz-column-gap:8px;column-gap:8px;margin-top:16px;-ms-flex-direction:row;flex-direction:row}verdocs-template-settings ::-webkit-input-placeholder{color:#aaaaaa}verdocs-template-settings ::-moz-placeholder{color:#aaaaaa}verdocs-template-settings :-ms-input-placeholder{color:#aaaaaa}verdocs-template-settings ::-ms-input-placeholder{color:#aaaaaa}verdocs-template-settings ::placeholder{color:#aaaaaa}`;

const MS_PER_DAY = 24 * 60 * 60 * 1000;
const VerdocsTemplateSettings = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.next = index.createEvent(this, "next");
        this.exit = index.createEvent(this, "exit");
        this.sdkError = index.createEvent(this, "sdkError");
        this.templateUpdated = index.createEvent(this, "templateUpdated");
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = jsSdk.VerdocsEndpoint.getDefault();
        /**
         * The template ID to edit.
         */
        this.templateId = '';
        this.name = null;
        this.visibility = 'private';
        this.sender = 'envelope_creator';
        this.sendReminders = false;
        this.initialReminder = 0;
        this.followupReminders = 0;
        this.dirty = false;
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        console.log('[SETTINGS] Loading template', this.templateId);
        this.unlistenToTemplate();
        Datastore.Store.subscribe('templates', this.templateId, () => jsSdk.getTemplate(this.endpoint, this.templateId), false, (template) => {
            console.log('[SETTINGS] Template Updated', template);
            this.template = template;
            this.name = template.name;
            this.visibility = template.visibility;
            this.sender = template.sender;
            this.sendReminders = template.initial_reminder !== null;
            this.initialReminder = template.initial_reminder ? Math.floor(template.initial_reminder / MS_PER_DAY) : null;
            this.followupReminders = template.followup_reminders ? Math.floor(template.followup_reminders / MS_PER_DAY) : null;
            this.dirty = false;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Datastore.Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[SETTINGS] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[SETTINGS] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[SETTINGS] Error with preview session', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new errors.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));
        }
    }
    handleCancel() {
        var _a;
        (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit();
    }
    handleSubmit() {
        jsSdk.updateTemplate(this.endpoint, this.templateId, {
            name: this.name,
            visibility: this.visibility,
            sender: this.sender,
            initial_reminder: this.sendReminders ? this.initialReminder * MS_PER_DAY : null,
            followup_reminders: this.sendReminders ? this.followupReminders * MS_PER_DAY : null,
        })
            .then(template => {
            var _a, _b;
            console.log('[SETTINGS] Template Updated', template);
            this.dirty = false;
            this.name = template.name;
            this.visibility = template.visibility;
            this.sender = template.sender;
            this.sendReminders = template.initial_reminder !== null;
            this.initialReminder = template.initial_reminder ? Math.floor(template.initial_reminder / MS_PER_DAY) : null;
            this.followupReminders = template.followup_reminders ? Math.floor(template.followup_reminders / MS_PER_DAY) : null;
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template, event: 'update' });
            (_b = this.next) === null || _b === void 0 ? void 0 : _b.emit();
        })
            .catch(e => {
            var _a, _b, _c, _d, _e;
            console.log('[SETTINGS] Error updating template', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new errors.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));
            Toast.VerdocsToast(((_e = (_d = e.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) || 'Error updating template, please try again later.');
        });
    }
    render() {
        if (!this.endpoint.session) {
            return (index.h(index.Host, null, index.h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        if (this.loading || !this.template) {
            return (index.h(index.Host, { class: "loading" }, index.h("verdocs-loader", null)));
        }
        return (index.h(index.Host, null, index.h("form", { onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, index.h("h5", null, "Settings"), index.h("div", { class: "row" }, index.h("verdocs-text-input", { id: "verdocs-field-name", label: "Template Name", value: this.name, autocomplete: "off", placeholder: "Template Name...", onInput: (e) => {
                this.name = e.target.value;
                this.dirty = true;
            } })), index.h("div", { class: "row" }, index.h("verdocs-select-input", { label: "Visibility", value: this.visibility, onInput: (e) => {
                this.visibility = e.target.value;
                this.dirty = true;
            }, options: [
                { value: 'private', label: 'Private' },
                { value: 'shared', label: 'Shared' },
                { value: 'public', label: 'Public' },
            ] })), index.h("div", { class: "row" }, index.h("verdocs-select-input", { label: "Owner for envelopes created from this template", value: this.sender, onInput: (e) => {
                this.sender = e.target.value;
                this.dirty = true;
            }, options: [
                { value: 'envelope_creator', label: 'Envelope Creator' },
                { value: 'template_owner', label: 'Template Owner' },
            ] })), index.h("div", { class: "row" }, index.h("label", null, "Send Reminders"), index.h("verdocs-switch", { checked: this.sendReminders, onCheckedChange: e => (this.sendReminders = e.detail) })), this.sendReminders && (index.h("div", { class: "row" }, index.h("verdocs-text-input", { id: "verdocs-field-name", label: "First Reminder (days)", value: String(this.initialReminder || 0), autocomplete: "off", placeholder: "Delay in days...", onInput: (e) => {
                this.initialReminder = +e.target.value;
                this.dirty = true;
            } }))), this.sendReminders && (index.h("div", { class: "row" }, index.h("verdocs-text-input", { id: "verdocs-field-name", label: "Follow-up Reminders (days)", value: String(this.followupReminders || 0), autocomplete: "off", placeholder: "Delay in days...", onInput: (e) => {
                this.followupReminders = +e.target.value;
                this.dirty = true;
            } }))), index.h("div", { class: "buttons" }, index.h("verdocs-button", { variant: "outline", label: "Cancel", size: "small", onClick: () => this.handleCancel() }), index.h("verdocs-button", { label: "Save", size: "small", onClick: () => this.handleSubmit(), disabled: !this.dirty })))));
    }
    get el() { return index.getElement(this); }
};
VerdocsTemplateSettings.style = verdocsTemplateSettingsCss();

exports.verdocs_template_settings = VerdocsTemplateSettings;
//# sourceMappingURL=verdocs-template-settings.entry.cjs.js.map

//# sourceMappingURL=verdocs-template-settings.cjs.entry.js.map