var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/*
 * Copyright 2022, OpenRemote Inc.
 *
 * See the CONTRIBUTORS.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
import { css, html, LitElement, unsafeCSS } from "lit";
import { InputType } from "@openremote/or-mwc-components/or-mwc-input";
import { customElement, property } from "lit/decorators.js";
import "@openremote/or-components/or-file-uploader";
import { DEFAULT_LANGUAGES, DefaultColor1, DefaultColor2, DefaultColor3, DefaultColor4, DefaultColor5, DefaultColor6, DefaultColor8, manager, Util, } from "@openremote/core";
import { i18next } from "@openremote/or-translate";
import { OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";
import { when } from 'lit/directives/when.js';
import ISO6391 from 'iso-639-1';
import { DefaultHeaderMainMenu, DefaultHeaderSecondaryMenu } from "../../../index";
let OrConfRealmCard = class OrConfRealmCard extends LitElement {
    constructor() {
        super(...arguments);
        this.realm = {};
        this.name = "";
        this.expanded = false;
        this.canRemove = false;
        this.logo = this.realm.logo;
        this.logoMobile = this.realm.logoMobile;
        this.favicon = this.realm.favicon;
        this.headerListPrimary = Object.keys(DefaultHeaderMainMenu);
        this.headerListSecondary = Object.keys(DefaultHeaderSecondaryMenu);
        this.commonLanguages = Object.entries(DEFAULT_LANGUAGES).map(entry => ISO6391.getName(entry[0]));
        this._languages = [];
        this.files = {};
    }
    connectedCallback() {
        const languageNames = ISO6391.getAllNames();
        this._languages = ISO6391.getAllCodes()
            .map((code, index) => ([code, languageNames[index]]))
            .sort((a, b) => a[1].localeCompare(b[1]));
        return super.connectedCallback();
    }
    _getColors() {
        var _a;
        const colors = {
            "--or-app-color1": unsafeCSS(DefaultColor1).toString(),
            "--or-app-color2": unsafeCSS(DefaultColor2).toString(),
            '--or-app-color3': unsafeCSS(DefaultColor3).toString(),
            '--or-app-color4': unsafeCSS(DefaultColor4).toString(),
            '--or-app-color5': unsafeCSS(DefaultColor5).toString(),
            '--or-app-color6': unsafeCSS(DefaultColor6).toString(),
            '--or-app-color8': unsafeCSS(DefaultColor8).toString()
        };
        if ((_a = this.realm) === null || _a === void 0 ? void 0 : _a.styles) {
            //TODO use regex for filtering and getting color codes CSS
            const css = this.realm.styles.slice(this.realm.styles.indexOf("{") + 1, this.realm.styles.indexOf("}"));
            css.split(";").forEach(function (value) {
                const col = value.split(":");
                if (col.length >= 2) {
                    colors[col[0].trim()] = col[1].trim();
                }
            });
        }
        return colors;
    }
    _setColor(key, value) {
        const colors = this._getColors();
        colors[key] = value;
        let css = ":host > * {";
        Object.entries(colors).forEach(([key, value]) => {
            css += key + ":" + value + ";";
        });
        css += "}";
        this.realm.styles = css;
        this.notifyConfigChange(this.realm);
    }
    _setHeader(keys, list) {
        var _a, _b;
        if (!this.realm.headers) {
            this.realm.headers = this.headerListSecondary.concat(this.headerListPrimary);
        }
        this.realm.headers = (_a = this.realm.headers) === null || _a === void 0 ? void 0 : _a.filter(function (ele) {
            return !list.includes(ele);
        });
        this.realm.headers = (_b = this.realm.headers) === null || _b === void 0 ? void 0 : _b.concat(keys);
        this.notifyConfigChange(this.realm);
    }
    _getImagePath(file, fileName) {
        if (file.type.startsWith("image/")) {
            const extension = file.name.slice(file.name.lastIndexOf('.'), file.name.length);
            return this.name + "/" + fileName + extension;
        }
        return null;
    }
    _setImageForUpload(file, fileName) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = this._getImagePath(file, fileName);
            if (path) {
                this.files[fileName] = {
                    name: fileName,
                    path: path,
                    contents: yield Util.blobToBase64(file),
                };
                this.realm[fileName] = path;
                this[fileName] = this.files[fileName].contents;
                this.requestUpdate();
                this.notifyConfigChange(this.realm);
                return this.files[fileName].contents;
            }
        });
    }
    // Public GET method for getting the files uploaded by the user.
    getFiles() {
        return this.files;
    }
    _showRemoveRealmDialog() {
        const dialogActions = [
            {
                actionName: "cancel",
                content: "cancel"
            },
            {
                default: true,
                actionName: "ok",
                content: "yes",
                action: () => {
                    this.dispatchEvent(new CustomEvent("remove"));
                }
            },
        ];
        showDialog(new OrMwcDialog()
            .setHeading(i18next.t('delete'))
            .setActions(dialogActions)
            .setContent(html `
                ${i18next.t('configuration.deleteRealmCustomizationConfirm')}
            `)
            .setStyles(html `
                <style>
                    .mdc-dialog__surface {
                        padding: 4px 8px;
                    }

                    #dialog-content {
                        padding: 24px;
                    }
                </style>
            `)
            .setDismissAction(null));
    }
    notifyConfigChange(config) {
        this.dispatchEvent(new CustomEvent("change", { detail: config }));
    }
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const colors = this._getColors();
        const app = this;
        const managerUrl = ((_a = manager.managerUrl) !== null && _a !== void 0 ? _a : "");
        // On an empty search; return the common language as set in DEFAULT_LANGUAGES
        // If searching, compare strings using lowercase. (with no maximum)
        const searchProvider = (search) => this._languages.filter(entry => {
            var _a;
            return (!search && this.commonLanguages.includes(entry[1])) ||
                (!search && ((_a = app.realm.notifications) === null || _a === void 0 ? void 0 : _a.languages.includes(entry[0]))) ||
                entry[1].toLowerCase().includes(search === null || search === void 0 ? void 0 : search.toLowerCase());
        });
        return html `
            <or-collapsible-panel .expanded="${app.expanded}">
                <div slot="header" class="header-container">
                    ${app.name}
                </div>
                <div slot="content" class="panel-content">
                    <div class="subheader">${i18next.t("configuration.main")}</div>
                    <or-mwc-input class="appTitle" .type="${InputType.TEXT}" .label="${i18next.t("configuration.realmTitle")}" value="${(_b = app.realm) === null || _b === void 0 ? void 0 : _b.appTitle}"
                                  @or-mwc-input-changed="${(e) => {
            app.realm.appTitle = e.detail.value;
            app.notifyConfigChange(app.realm);
        }}"
                    ></or-mwc-input>
                    <or-mwc-input class="language" .type="${InputType.SELECT}" .label="${i18next.t("configuration.defaultLanguage")}" value="${(_c = app.realm) === null || _c === void 0 ? void 0 : _c.language}"
                                  .options="${Object.entries(DEFAULT_LANGUAGES).map(([key, value]) => [key, i18next.t(value)])}"
                                  @or-mwc-input-changed="${(e) => {
            app.realm.language = e.detail.value;
            app.notifyConfigChange(app.realm);
        }}"
                    ></or-mwc-input>
                    <div class="logo-group">
                        <div class="subheader">${i18next.t("configuration.images")}</div>
                        <div class="d-inline-flex">
                            <or-file-uploader .title="${i18next.t('configuration.logo')}"
                                              @change="${(e) => __awaiter(this, void 0, void 0, function* () { return yield app._setImageForUpload(e.detail.value[0], "logo"); })}"
                                              .src="${app.logo ? app.logo : app.realm.logo}" .managerUrl="${managerUrl}"></or-file-uploader>
                            <or-file-uploader .title="${i18next.t('configuration.logoMobile')}"
                                              @change="${(e) => __awaiter(this, void 0, void 0, function* () { return yield app._setImageForUpload(e.detail.value[0], "logoMobile"); })}"
                                              .src="${app.logoMobile ? app.logoMobile : app.realm.logoMobile}" .managerUrl="${managerUrl}"></or-file-uploader>
                            <or-file-uploader .title="${html `Favicon`}"
                                              @change="${(e) => __awaiter(this, void 0, void 0, function* () { return yield app._setImageForUpload(e.detail.value[0], "favicon"); })}"
                                              .src="${app.favicon ? app.favicon : app.realm.favicon}" .managerUrl="${managerUrl}"></or-file-uploader>
                        </div>
                    </div>
                    <div class="color-group">
                        <div class="subheader">${i18next.t('configuration.realmColors')}</div>
                        <div>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color4"]}"
                                          .label="${i18next.t('configuration.--or-app-color4')}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color4", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color5"]}"
                                          .label="${i18next.t('configuration.--or-app-color5')}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color5", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color6"]}"
                                          .label="${i18next.t("configuration.--or-app-color6")}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color6", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color1"]}"
                                          .label="${i18next.t("configuration.--or-app-color1")}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color1", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color2"]}"
                                          .label="${i18next.t("configuration.--or-app-color2")}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color2", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color3"]}"
                                          .label="${i18next.t("configuration.--or-app-color3")}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color3", e.detail.value)}"></or-mwc-input>
                            <or-mwc-input class="color-item" .type="${InputType.COLOUR}" value="${colors["--or-app-color8"]}"
                                          .label="${i18next.t("configuration.--or-app-color8")}"
                                          @or-mwc-input-changed="${(e) => app._setColor("--or-app-color8", e.detail.value)}"></or-mwc-input>
                        </div>
                    </div>
                    <div class="header-group">
                        <div class="subheader">${i18next.t("configuration.navigation")}</div>
                        <span>${i18next.t("configuration.navigationDescription")}</span>
                        <div>
                            <or-mwc-input
                                    .type="${InputType.SELECT}" multiple
                                    class="header-item"
                                    .label="${i18next.t("configuration.primaryNavigation")}"
                                    .value="${!!app.realm.headers ? (_d = app.realm.headers) === null || _d === void 0 ? void 0 : _d.filter(function (ele) {
            return app.headerListPrimary.includes(ele);
        }) : app.headerListPrimary}"
                                    .options="${app.headerListPrimary}"
                                    @or-mwc-input-changed="${(e) => app._setHeader(e.detail.value, app.headerListPrimary)}"
                            ></or-mwc-input>
                            <or-mwc-input
                                    .type="${InputType.SELECT}" multiple
                                    class="header-item"
                                    .label="${i18next.t("configuration.secondaryNavigation")}"
                                    .value="${!!app.realm.headers ? (_e = app.realm.headers) === null || _e === void 0 ? void 0 : _e.filter(function (ele) {
            return app.headerListSecondary.includes(ele);
        }) : app.headerListSecondary}"
                                    .options="${app.headerListSecondary}"
                                    @or-mwc-input-changed="${(e) => app._setHeader(e.detail.value, app.headerListSecondary)}"
                            ></or-mwc-input>
                        </div>
                    </div>
                    <div class="header-group">
                        <div class="subheader">${i18next.t("configuration.notificationLanguages")}</div>
                        <span>${i18next.t("configuration.notificationLanguagesDesc")}</span>
                        <div>
                            <or-mwc-input
                                    .type="${InputType.SELECT}" multiple
                                    class="header-item"
                                    searchLabel="configuration.notificationLanguagesLabel"
                                    .label="${i18next.t("configuration.notificationLanguages")}"
                                    .value="${((_f = app.realm.notifications) === null || _f === void 0 ? void 0 : _f.languages) || []}"
                                    .options="${this._languages}"
                                    .searchProvider="${searchProvider}"
                                    @or-mwc-input-changed="${(e) => {
            var _a;
            const newLanguages = e.detail.value;
            const currentDefault = (_a = app.realm.notifications) === null || _a === void 0 ? void 0 : _a.defaultLanguage;
            app.realm.notifications = {
                languages: newLanguages,
                defaultLanguage: (newLanguages === null || newLanguages === void 0 ? void 0 : newLanguages.includes(currentDefault)) ? currentDefault : newLanguages === null || newLanguages === void 0 ? void 0 : newLanguages[0]
            };
            app.notifyConfigChange(app.realm);
            this.requestUpdate(); // force render
        }}"
                            ></or-mwc-input>
                            ${when(((_h = (_g = app.realm.notifications) === null || _g === void 0 ? void 0 : _g.languages) === null || _h === void 0 ? void 0 : _h.length) > 0, () => {
            var _a;
            return html `
                                <or-mwc-input
                                        .type="${InputType.SELECT}"
                                        class="header-item"
                                        .label="${i18next.t("configuration.defaultLanguage")}"
                                        .value="${((_a = app.realm.notifications) === null || _a === void 0 ? void 0 : _a.defaultLanguage) || []}"
                                        .options="${this._languages.filter(entry => { var _a; return (_a = app.realm.notifications) === null || _a === void 0 ? void 0 : _a.languages.includes(entry[0]); })}"
                                        @or-mwc-input-changed="${(e) => {
                app.realm.notifications.defaultLanguage = e.detail.value;
                app.notifyConfigChange(app.realm);
                this.requestUpdate(); // force render
            }}"
                                ></or-mwc-input>
                            `;
        }, () => html `
                                <or-mwc-input
                                        .type="${InputType.SELECT}" disabled
                                        class="header-item"
                                        .label="${i18next.t("configuration.defaultLanguage")}"
                                ></or-mwc-input>
                            `)}
                        </div>
                    </div>

                    ${when(app.canRemove, () => html `
                        <or-mwc-input outlined id="remove-realm" .type="${InputType.BUTTON}"
                                      label="configuration.deleteRealmCustomization"
                                      @or-mwc-input-changed="${() => { app._showRemoveRealmDialog(); }}"
                        ></or-mwc-input>
                    `)}
                </div>
            </or-collapsible-panel>
        `;
    }
};
OrConfRealmCard.styles = css `
      .language {
        width: 100%;
        padding: 10px 0px;
        max-width: 800px;
      }

      .appTitle {
        width: 100%;
        max-width: 800px;
        padding: 10px 0px;
      }

      .header-group .header-item {
        width: 100%;
        padding: 10px 0px;
        max-width: 800px;
      }

      .color-group .color-item {
        width: 100%;
      }

      .logo-group {
        width: 100%;
      }

      @media screen and (max-width: 768px) {
        .logo-group or-file-uploader {
          min-width: calc(50% - 6px);
          padding: 0 12px 12px 0!important;
        }

        .logo-group or-file-uploader:nth-child(2n + 2){
          padding: 0 0 12px 0!important;
        }

        .logo-group .d-inline-flex{
          display: flex;
          flex-wrap: wrap;
        }
      }

      .logo-group or-file-uploader {
        padding: 0 24px 12px 0;
      }

      #remove-realm {
        margin: 12px 0 0 0;
      }

      .subheader {
        padding: 10px 0 4px;
        font-weight: bolder;
      }

      .d-inline-flex {
        display: inline-flex;
      }

      .panel-content {
        padding: 0 24px 24px;
      }

      .description {
        font-size: 12px;
      }

      or-collapsible-panel {
        margin-bottom: 10px;
      }
    `;
__decorate([
    property({ attribute: false })
], OrConfRealmCard.prototype, "realm", void 0);
__decorate([
    property({ attribute: true })
], OrConfRealmCard.prototype, "name", void 0);
__decorate([
    property({ type: Boolean })
], OrConfRealmCard.prototype, "expanded", void 0);
__decorate([
    property()
], OrConfRealmCard.prototype, "canRemove", void 0);
OrConfRealmCard = __decorate([
    customElement("or-conf-realm-card")
], OrConfRealmCard);
export { OrConfRealmCard };
//# sourceMappingURL=or-conf-realm-card.js.map