import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@material/web/textfield/filled-text-field.js';
import '@material/web/select/outlined-select';
import '@material/web/button/elevated-button.js';
import '@material/web/chips/chip-set.js';
import '@material/web/chips/assist-chip.js';
import '@material/web/chips/filter-chip.js';
import gql from 'graphql-tag';
import { css, html, LitElement, nothing } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { connect } from 'pwa-helpers/connect-mixin';
import { i18next } from '@operato/i18n';
import { client } from '@operato/graphql';
import { navigate, store } from '@operato/shell';
import { OxPrompt } from '@operato/popup/ox-prompt.js';
import { hasPrivilege } from '@things-factory/auth-base/dist-client';
import { styles as MDTypeScaleStyles } from '@material/web/typography/md-typescale-styles';
let BoardInfo = class BoardInfo extends connect(store)(LitElement) {
    constructor() {
        super(...arguments);
        this.boardGroupList = [];
        this.playGroupList = [];
        this.showTarget = false;
        this.enableModeller = false;
        this.targetDomains = [];
        this.targetGroups = [];
    }
    render() {
        var _a, _b;
        var board = this.board || { name: '', description: '', playGroups: [] };
        var boardGroupList = this.boardGroupList || [];
        var playGroupList = (this.playGroupList || []).map(group => {
            return Object.assign(Object.assign({}, group), { checked: false });
        });
        (board.playGroups || []).map(group => {
            var playGroup = playGroupList.find(g => g.id == group.id);
            if (playGroup) {
                playGroup.checked = true;
            }
        });
        return html `
      ${board.thumbnail ? html ` <img src=${board.thumbnail} /> ` : html ``}

      <form class="md-typescale-body-medium">
        <fieldset>
          <legend class="md-typescale-label-large-prominent">${i18next.t('label.information')}</legend>
          <div oneline>
            <md-filled-text-field
              label=${String(i18next.t('label.name'))}
              type="text"
              .value=${board.name}
              @change=${e => (this.board = Object.assign(Object.assign({}, this.board), { name: e.target.value }))}
              ?disabled=${!this.enableModeller}
            ></md-filled-text-field>

            ${this.enableModeller
            ? html `
                  <md-icon
                    @click=${() => {
                this.showTarget = !this.showTarget;
            }}
                    tail
                    >${this.showTarget ? 'arrow_drop_up' : 'arrow_drop_down'}</md-icon
                  >
                `
            : nothing}
          </div>
          ${this.showTarget
            ? html `
                <div fullwidth target>
                  <label class="md-typescale-label-meium-prominent">${i18next.t('label.board-copy')}</label>
                  <div oneline>
                    <md-outlined-select
                      label=${String(i18next.t('label.domain'))}
                      @change=${e => {
                this.targetSubdomain = e.target.value;
                this.getGroupsByDomain(this.targetSubdomain);
            }}
                      .value=${this.targetSubdomain || ''}
                      ?disabled=${!this.enableModeller}
                    >
                      <md-select-option aria-label="blank"></md-select-option>
                      ${this.targetDomains.map(domain => html `
                          <md-select-option
                            value=${domain.subdomain}
                            ?selected=${domain.subdomain == this.targetSubdomain}
                          >
                            <div slot="headline">${domain.name}</div>
                          </md-select-option>
                        `)}
                    </md-outlined-select>

                    <md-outlined-select
                      label=${String(i18next.t('label.group'))}
                      @change=${e => (this.targetGroupId = e.target.value)}
                      .value=${this.targetGroupId || ''}
                      ?disabled=${!this.enableModeller}
                    >
                      <md-select-option aria-label="blank"></md-select-option>
                      ${this.targetGroups.map(group => html `
                          <md-select-option value=${group.id} ?selected=${group.id == this.targetGroupId}>
                            <div slot="headline">${group.name}</div>
                          </md-select-option>
                        `)}
                    </md-outlined-select>
                  </div>

                  <md-chip-set oneline>
                    <md-assist-chip
                      elevated
                      label=${String(i18next.t('button.copy'))}
                      ?disabled=${!this.enableModeller ||
                !((_a = this.original) === null || _a === void 0 ? void 0 : _a.name) ||
                !this.board.name ||
                !this.targetSubdomain ||
                (this.original.name == this.board.name && this.subdomain == this.targetSubdomain)}
                      @click=${this.cloneBoard.bind(this)}
                      right
                    >
                      <md-icon slot="icon">content_copy</md-icon>
                    </md-assist-chip>

                    <md-assist-chip
                      elevated
                      label=${String(i18next.t('button.export'))}
                      @click=${this.exportBoard.bind(this)}
                    >
                      <md-icon slot="icon">download</md-icon>
                    </md-assist-chip>
                  </md-chip-set>
                </div>
              `
            : nothing}

          <md-filled-text-field
            oneline
            label=${String(i18next.t('label.description'))}
            .value=${board.description}
            @change=${e => (this.board = Object.assign(Object.assign({}, this.board), { description: e.target.value }))}
            ?disabled=${!this.enableModeller}
          ></md-filled-text-field>

          <md-outlined-select
            oneline
            label=${String(i18next.t('label.group'))}
            @change=${e => (this.board = Object.assign(Object.assign({}, this.board), { groupId: e.target.value }))}
            .value=${this.groupId || ''}
            .displayText=${(_b = boardGroupList === null || boardGroupList === void 0 ? void 0 : boardGroupList.find(item => item.id == this.groupId)) === null || _b === void 0 ? void 0 : _b.name}
            ?disabled=${!this.enableModeller}
          >
            <md-select-option aria-label="blank"></md-select-option>
            ${boardGroupList.map(item => html `
                <md-select-option value=${item.id} ?selected=${item.id == this.groupId}>
                  <div slot="headline">${item.name}</div>
                </md-select-option>
              `)}
          </md-outlined-select>

          <md-chip-set oneline>
            <md-assist-chip
              danger
              elevated
              ?disabled=${!this.enableModeller}
              label=${String(i18next.t('button.delete'))}
              @click=${this.deleteBoard.bind(this)}
            >
              <md-icon slot="icon">delete_outline</md-icon>
            </md-assist-chip>

            <md-assist-chip
              elevated
              ?disabled=${!this.enableModeller}
              label=${String(i18next.t('button.save'))}
              @click=${this.updateBoard.bind(this)}
              right
            >
              <md-icon slot="icon">save</md-icon>
            </md-assist-chip>
            <md-assist-chip
              elevated
              ?disabled=${!this.enableModeller}
              label=${String(i18next.t('button.edit'))}
              @click=${() => navigate(`${'board-modeller/' + this.boardId}`)}
            >
              <md-icon slot="icon">drive_file_rename_outline</md-icon>
            </md-assist-chip>
          </md-chip-set>
        </fieldset>

        <fieldset>
          <legend class="md-typescale-label-large-prominent">${i18next.t('label.status')}</legend>
          <div oneline>
            <label class="md-typescale-label-meium">${i18next.t('label.creator')}</label>
            <md-icon dim>person</md-icon>
            <div name title=${(board.creator && board.creator.name) || 'anonymous'}>
              ${(board.creator && board.creator.name) || 'anonymous'}
            </div>
            <md-icon dim>schedule</md-icon> ${new Date(board.createdAt).toLocaleString()}
          </div>

          <div oneline>
            <label class="md-typescale-label-meium">${i18next.t('label.updater')}</label>
            <md-icon dim>person</md-icon>
            <div name title=${(board.updater && board.updater.name) || 'anonymouse'}>
              ${(board.updater && board.updater.name) || 'anonymouse'}
            </div>
            <md-icon dim>schedule</md-icon> ${new Date(board.updatedAt).toLocaleString()}
          </div>

          <div oneline>
            <label class="md-typescale-label-meium">${i18next.t('label.state')}</label>
            <md-icon dim>signpost</md-icon> ${(board.state || '').toUpperCase()}
            <md-icon dim>pin</md-icon> ${board.version}
            <md-chip-set>
              <md-assist-chip
                elevated
                label=${String(i18next.t('button.release'))}
                ?disabled=${!this.enableModeller || !this.isReleasable}
                @click=${this.releaseBoard.bind(this)}
                right
              >
                <md-icon slot="icon">new_releases</md-icon>
              </md-assist-chip>
            </md-chip-set>
          </div>
        </fieldset>

        <fieldset>
          <legend class="md-typescale-label-large-prominent">${i18next.t('label.play-group')}</legend>
          <md-chip-set oneline>
            ${playGroupList.map(item => html `
                <md-filter-chip
                  label=${item.name}
                  ?selected=${item.checked}
                  @click=${e => {
            e.target.selected ? this.joinPlayGroup(item) : this.leavePlayGroup(item);
        }}
                ></md-filter-chip>
              `)}
          </md-chip-set>
        </fieldset>
      </form>
    `;
    }
    stateChanged(state) {
        var _a, _b, _c;
        this.subdomain = (_b = (_a = state.app) === null || _a === void 0 ? void 0 : _a.domain) === null || _b === void 0 ? void 0 : _b.subdomain;
        this.targetSubdomain = (_c = this.targetSubdomain) !== null && _c !== void 0 ? _c : this.subdomain;
    }
    async firstUpdated() {
        this.enableModeller = await hasPrivilege({ privilege: 'mutation', category: 'board' });
        this.refresh();
    }
    async refresh() {
        var _a;
        var response = (await client.query({
            query: gql `
          query FetchBoardById($id: String!) {
            board(id: $id) {
              id
              name
              description
              model
              group {
                id
                name
              }
              playGroups {
                id
                name
              }
              thumbnail
              createdAt
              creator {
                id
                name
              }
              state
              version
              updatedAt
              updater {
                id
                name
              }
            }

            groups {
              items {
                id
                name
                description
              }
            }

            playGroups {
              items {
                id
                name
                description
              }
              total
            }

            domainsWithPrivilege(privilege: "mutation", category: "board") {
              name
              subdomain
            }
          }
        `,
            variables: { id: this.boardId }
        })).data;
        this.board = response.board;
        this.boardGroupList = response.groups.items;
        this.playGroupList = response.playGroups.items;
        this.original = Object.assign({}, this.board);
        this.groupId = (_a = this.board.group) === null || _a === void 0 ? void 0 : _a.id;
        this.targetDomains = response.domainsWithPrivilege;
        this.targetGroups = response.groups.items;
        this.targetGroupId = this.groupId;
    }
    async getGroupsByDomain(subdomain) {
        this.targetGroups = [];
        this.targetGroupId = '';
        if (!subdomain) {
            return;
        }
        var response = (await client.query({
            query: gql `
          query {
            groups {
              items {
                id
                name
                description
              }
            }
          }
        `,
            variables: { id: this.boardId },
            context: {
                headers: {
                    'x-things-factory-domain': subdomain
                }
            }
        })).data;
        this.targetGroups = response.groups.items;
    }
    get isReleasable() {
        if (!this.board || this.board.state == 'released') {
            return false;
        }
        const { name, description, groupId } = this.board;
        return (this.original &&
            this.original.name == name &&
            this.original.description == description &&
            this.original.groupId == groupId);
    }
    async cloneBoard() {
        if (!this.original.name || (this.board.name == this.original.name && this.subdomain == this.targetSubdomain)) {
            document.dispatchEvent(new CustomEvent('notify', {
                detail: {
                    level: 'error',
                    message: i18next.t('error.name must be unique from the original board', { name: this.original.name })
                }
            }));
            return;
        }
        const { id, name, description } = this.board;
        this.dispatchEvent(new CustomEvent('clone-board', {
            detail: {
                id,
                name,
                description,
                targetSubdomain: this.targetSubdomain,
                targetGroupId: this.targetGroupId
            },
            bubbles: true,
            composed: true
        }));
        this.close();
    }
    async exportBoard() {
        const board = Object.assign(Object.assign({}, this.board), { model: JSON.parse(this.board.model) });
        const json = JSON.stringify(board, null, 2);
        const blob = new Blob([json], { type: 'application/json;charset=utf-8' });
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = `${board.name}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(blobUrl);
    }
    async releaseBoard() {
        const { id } = this.board;
        this.dispatchEvent(new CustomEvent('release-board', {
            detail: {
                id
            },
            bubbles: true,
            composed: true
        }));
    }
    async updateBoard() {
        const { id, name, description, groupId } = this.board;
        /* model 정보를 제외하고 업데이트 */
        this.dispatchEvent(new CustomEvent('update-board', {
            detail: { id, name, description, groupId },
            bubbles: true,
            composed: true
        }));
    }
    async deleteBoard() {
        if (await OxPrompt.open({
            title: i18next.t('text.are_you_sure'),
            text: i18next.t('text.sure_to_x', { x: i18next.t('text.delete') }),
            confirmButton: { text: i18next.t('button.confirm') },
            cancelButton: { text: i18next.t('button.cancel') }
        })) {
            this.dispatchEvent(new CustomEvent('delete-board', {
                detail: this.board,
                bubbles: true,
                composed: true
            }));
            this.close();
        }
    }
    async joinPlayGroup(group) {
        this.dispatchEvent(new CustomEvent('join-playgroup', {
            detail: {
                board: this.board,
                playGroup: group
            },
            bubbles: true,
            composed: true
        }));
    }
    async leavePlayGroup(group) {
        this.dispatchEvent(new CustomEvent('leave-playgroup', {
            detail: {
                board: this.board,
                playGroup: group
            },
            bubbles: true,
            composed: true
        }));
    }
    close() {
        history.back();
    }
};
BoardInfo.styles = [
    MDTypeScaleStyles,
    css `
      :host {
        position: relative;
        display: block;
        background-color: var(--md-sys-color-surface);
        color: var(--md-sys-color-on-surface);

        --md-filled-field-top-space: 12px;
        --md-filled-field-bottom-space: 12px;
        --md-filled-field-leading-space: 12px;
        --md-filled-field-trailing-space: 12px;

        --md-outlined-field-top-space: 12px;
        --md-outlined-field-bottom-space: 12px;
        --md-outlined-field-leading-space: 12px;
        --md-outlined-field-trailing-space: 12px;
      }

      img {
        object-fit: contain;
        max-width: 100%;
        max-height: 100%;
        border-bottom: 2px solid rgba(0, 0, 0, 0.1);
      }

      form {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-gap: 10px 0;
        grid-auto-rows: minmax(24px, auto);
        padding: var(--spacing-large);
        align-items: center;
      }

      md-outlined-select,
      md-filled-text-field {
        flex: 1;
        padding: 4px 0;
        min-width: unset;
      }

      md-chip-set {
        flex: 1;
        display: flex;
        gap: 4px;
      }

      fieldset {
        display: contents;
      }

      legend {
        grid-column: span 12;
        padding: var(--legend-padding);
        color: var(--md-sys-color-primary);
        text-transform: capitalize;
      }

      label {
        text-transform: capitalize;
      }

      md-icon[dim] {
        font-variation-settings: 'FILL' 1;
        --md-icon-size: 14px;
        color: var(--md-sys-color-outline-variant);
      }

      [name] {
        max-width: 70px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      [danger] {
        --md-assist-chip-elevated-container-color: var(--md-sys-color-error);
        --md-assist-chip-label-text-color: var(--md-sys-color-on-error);
        --md-assist-chip-leading-icon-color: var(--md-sys-color-on-error);
      }

      [fullwidth] {
        grid-column: span 12 / auto;
        display: flex;
        flex-direction: column;
        gap: 4px;
      }

      [oneline] {
        grid-column: span 12 / auto;
        display: flex;
        flex-direction: row;
        gap: 4px;
        align-items: center;
      }

      [oneline] md-filled-text-field,
      [oneline] select {
        flex: 1;
      }

      [right] {
        margin-left: auto;
      }

      @media screen and (max-width: 460px) {
        :host {
          width: 100vw;
        }
      }
    `
];
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], BoardInfo.prototype, "boardId", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], BoardInfo.prototype, "groupId", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], BoardInfo.prototype, "board", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], BoardInfo.prototype, "boardGroupList", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], BoardInfo.prototype, "playGroupList", void 0);
__decorate([
    state(),
    __metadata("design:type", Boolean)
], BoardInfo.prototype, "showTarget", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], BoardInfo.prototype, "subdomain", void 0);
__decorate([
    state(),
    __metadata("design:type", Boolean)
], BoardInfo.prototype, "enableModeller", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], BoardInfo.prototype, "targetDomains", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], BoardInfo.prototype, "targetGroups", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], BoardInfo.prototype, "targetSubdomain", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], BoardInfo.prototype, "targetGroupId", void 0);
BoardInfo = __decorate([
    customElement('board-basic-info')
], BoardInfo);
export { BoardInfo };
//# sourceMappingURL=board-basic-info.js.map