import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@material/web/button/elevated-button.js';
import gql from 'graphql-tag';
import { css, html, LitElement } 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';
let ProcessInfo = class ProcessInfo extends connect(store)(LitElement) {
    constructor() {
        super(...arguments);
        this.processGroupList = [];
        this.showTarget = false;
        this.targetDomains = [];
        this.targetGroups = [];
    }
    render() {
        var _a;
        var process = this.process || { name: '', description: '' };
        var processGroupList = this.processGroupList || [];
        return html `
      ${process.thumbnail ? html ` <img src=${process.thumbnail} /> ` : html ``}

      <form>
        <fieldset>
          <legend>${i18next.t('label.information')}</legend>
          <label>${i18next.t('label.name')}</label>
          <div oneline>
            <input
              type="text"
              .value=${process.name}
              @change=${e => (this.process = Object.assign(Object.assign({}, this.process), { name: e.target.value }))}
              ?disabled=${!this.enableModeller}
            />
            ${this.enableModeller
            ? html `
                  <md-icon
                    @click=${() => {
                this.showTarget = !this.showTarget;
            }}
                    tail
                    >${this.showTarget ? 'arrow_drop_up' : 'arrow_drop_down'}</md-icon
                  >
                `
            : html ``}
          </div>
          ${this.showTarget
            ? html `
                <div fullwidth target>
                  <label>${i18next.t('label.process-copy')}</label>
                  <div oneline>
                    <select
                      @change=${e => {
                this.targetSubdomain = e.target.value;
                this.getGroupsByDomain(this.targetSubdomain);
            }}
                      placeholder="choose domain ..."
                      .value=${this.targetSubdomain || ''}
                      ?disabled=${!this.enableModeller}
                    >
                      <option value=""></option>
                      ${this.targetDomains.map(domain => html `
                            <option .value=${domain.subdomain} ?selected=${domain.subdomain == this.targetSubdomain}>
                              ${domain.name}
                            </option>
                          `)}
                    </select>

                    <select
                      @change=${e => (this.targetGroupId = e.target.value)}
                      placeholder="choose group ..."
                      .value=${this.targetGroupId || ''}
                      ?disabled=${!this.enableModeller}
                    >
                      <option value=""></option>
                      ${this.targetGroups.map(group => html `
                            <option .value=${group.id} ?selected=${group.id == this.targetGroupId}>
                              ${group.description}
                            </option>
                          `)}
                    </select>
                  </div>
                  <div oneline>
                    <md-elevated-button
                      type="button"
                      ?disabled=${!this.enableModeller ||
                !((_a = this.original) === null || _a === void 0 ? void 0 : _a.name) ||
                !this.process.name ||
                !this.targetSubdomain ||
                (this.original.name == this.process.name && this.subdomain == this.targetSubdomain)}
                      @click=${this.cloneProcess.bind(this)}
                      right
                    >
                      <md-icon slot="icon">content_copy</md-icon>${String(i18next.t('button.copy'))}
                    </md-elevated-button>
                    <md-elevated-button type="button" @click=${this.exportProcess.bind(this)} icon="download">
                      <md-icon slot="icon">download</md-icon>${String(i18next.t('button.export'))}
                    </md-elevated-button>
                  </div>
                </div>
              `
            : html ``}

          <label>${i18next.t('label.description')}</label>
          <input
            type="text"
            .value=${process.description}
            @change=${e => (this.process = Object.assign(Object.assign({}, this.process), { description: e.target.value }))}
            ?disabled=${!this.enableModeller}
          />

          <label>${i18next.t('label.group')}</label>
          <select
            @change=${e => (this.process = Object.assign(Object.assign({}, this.process), { groupId: e.target.value }))}
            .value=${this.groupId || ''}
            ?disabled=${!this.enableModeller}
          >
            <option value="" ?selected=${'' == this.groupId}></option>
            ${processGroupList.map(item => html ` <option .value=${item.id} ?selected=${item.id == this.groupId}>${item.description}</option> `)}
          </select>
          <label>${i18next.t('label.creator')}</label>
          <span>
            <md-icon>person</md-icon> ${(process.creator && process.creator.name) || 'anonymous'}
            <md-icon>schedule</md-icon> ${new Date(process.createdAt).toLocaleString()}
          </span>

          <label>${i18next.t('label.updater')}</label>
          <span>
            <md-icon>person</md-icon> ${(process.updater && process.updater.name) || 'anonymouse'}
            <md-icon>schedule</md-icon> ${new Date(process.updatedAt).toLocaleString()}
          </span>

          <label>${i18next.t('label.state')}</label>
          <span state>
            <div oneline>
              <md-icon>signpost</md-icon> ${(process.state || '').toUpperCase()}
              <md-icon>pin</md-icon> ${process.version}
            </div>
            <md-elevated-button
              type="button"
              ?disabled=${!this.enableModeller || !this.isReleasable}
              @click=${this.releaseProcess.bind(this)}
            >
              <md-icon slot="icon">new_releases</md-icon>${String(i18next.t('button.release'))}
            </md-elevated-button>
          </span>

          <div buttons>
            <md-elevated-button
              type="button"
              danger
              ?disabled=${!this.enableModeller}
              @click=${this.deleteProcess.bind(this)}
            >
              <md-icon slot="icon">delete_outline</md-icon>${String(i18next.t('button.delete'))}
            </md-elevated-button>
            <md-elevated-button type="button" ?disabled=${!this.enableModeller} @click=${this.updateProcess.bind(this)}>
              <md-icon slot="icon">save</md-icon>${String(i18next.t('button.save'))}
            </md-elevated-button>
            <md-elevated-button
              type="button"
              ?disabled=${!this.enableModeller}
              @click=${() => navigate(`${'process-modeller/' + this.processId}`)}
            >
              <md-icon slot="icon">drive_file_rename_outline</md-icon>${String(i18next.t('button.edit'))}
            </md-elevated-button>
          </div>
        </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;
    }
    firstUpdated() {
        this.refresh();
    }
    async refresh() {
        var _a;
        var response = (await client.query({
            query: gql `
          query FetchProcessById($id: String!) {
            process(id: $id) {
              id
              name
              description
              model
              group {
                id
                name
              }
              thumbnail
              createdAt
              creator {
                id
                name
              }
              state
              version
              updatedAt
              updater {
                id
                name
              }
            }

            processGroups {
              items {
                id
                name
                description
              }
            }

            domainsWithPrivilege(privilege: "mutation", category: "process") {
              name
              subdomain
            }
          }
        `,
            variables: { id: this.processId }
        })).data;
        this.process = response.process;
        this.processGroupList = response.processGroups.items;
        this.original = Object.assign({}, this.process);
        this.groupId = (_a = this.process.group) === null || _a === void 0 ? void 0 : _a.id;
        this.targetDomains = response.domainsWithPrivilege;
        this.targetGroups = response.processGroups.items;
        this.targetGroupId = this.groupId;
    }
    async getGroupsByDomain(subdomain) {
        this.targetGroups = [];
        this.targetGroupId = '';
        if (!subdomain) {
            return;
        }
        var response = (await client.query({
            query: gql `
          query {
            processGroups {
              items {
                id
                name
                description
              }
            }
          }
        `,
            variables: { id: this.processId },
            context: {
                headers: {
                    'x-things-factory-domain': subdomain
                }
            }
        })).data;
        this.targetGroups = response.groups.items;
    }
    get isReleasable() {
        if (!this.process || this.process.state == 'released') {
            return false;
        }
        const { name, description, groupId } = this.process;
        return (this.original &&
            this.original.name == name &&
            this.original.description == description &&
            this.original.groupId == groupId);
    }
    async cloneProcess() {
        if (!this.original.name || (this.process.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 process', { name: this.original.name })
                }
            }));
            return;
        }
        const { id, name, description } = this.process;
        this.dispatchEvent(new CustomEvent('clone-process', {
            detail: {
                id,
                name,
                description,
                targetSubdomain: this.targetSubdomain,
                targetGroupId: this.targetGroupId
            },
            bubbles: true,
            composed: true
        }));
        this.close();
    }
    async exportProcess() {
        const process = Object.assign(Object.assign({}, this.process), { model: JSON.parse(this.process.model) });
        const json = JSON.stringify(process, 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 = `${process.name}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(blobUrl);
    }
    async releaseProcess() {
        const { id } = this.process;
        this.dispatchEvent(new CustomEvent('release-process', {
            detail: {
                id
            },
            bubbles: true,
            composed: true
        }));
    }
    async updateProcess() {
        const { id, name, description, groupId } = this.process;
        /* model 정보를 제외하고 업데이트 */
        this.dispatchEvent(new CustomEvent('update-process', {
            detail: { id, name, description, groupId },
            bubbles: true,
            composed: true
        }));
    }
    async deleteProcess() {
        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-process', {
                detail: this.process,
                bubbles: true,
                composed: true
            }));
            this.close();
        }
    }
    close() {
        history.back();
    }
};
ProcessInfo.styles = [
    css `
      :host {
        display: block;
        background-color: var(--main-section-background-color);
        position: relative;

        --form-grid-gap: 2px 0;
        --input-field-padding: var(--padding-default);
        --legend-padding: var(--padding-default) 0 var(--padding-narrow) 0;
        --mdc-button-horizontal-padding: var(--padding-default);
      }

      img {
        display: block;

        margin: auto;
        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: var(--form-grid-gap);
        grid-auto-rows: minmax(24px, auto);
        padding: var(--padding-wide);
        align-items: center;
      }

      [buttons] {
        grid-column: span 12;
        padding: var(--padding-default) 0;
        text-align: right;
      }

      [buttons] * {
        margin: 0 0 0 var(--margin-narrow);
      }

      [danger] {
        float: left;
        margin: 0 var(--margin-narrow) 0 0;
        --mdc-theme-primary: var(--status-danger-color);
      }

      fieldset {
        display: contents;
      }

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

      label {
        grid-column: span 12;
        text-transform: capitalize;
        color: var(--label-color);
        font: var(--label-font);
      }

      span {
        grid-column: span 12;
        border-bottom: var(--border-dark-color);
        margin-bottom: var(--margin-default);
        padding-bottom: var(--padding-narrow);
        font: var(--input-field-font);
      }

      span[state] {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      span md-icon {
        --md-icon-size: var(--fontsize-large);
        vertical-align: middle;
        color: var(--primary-color);
      }

      input,
      table,
      select,
      textarea,
      [custom-input] {
        grid-column: span 12;

        border: var(--input-field-border);
        border-radius: var(--input-field-border-radius);
        margin-bottom: var(--margin-default);
        padding: var(--input-field-padding);
        font: var(--input-field-font);
      }

      md-icon[tail] {
        margin-bottom: var(--margin-default);
      }

      input[type='checkbox'],
      input[type='radio'] {
        place-self: center;
        margin: 0;
        grid-column: 1;
      }

      input[type='checkbox'] + label,
      input[type='radio'] + label {
        text-align: left;
        grid-column: span 11 / auto;

        font: var(--form-sublabel-font);
        color: var(--form-sublabel-color);
      }

      input:focus {
        outline: none;
        border: 1px solid var(--focus-background-color);
      }

      div[fullwidth] {
        grid-column: span 12 / auto;
        border-bottom: var(--border-dark-color);

        display: flex;
        flex-direction: column;
        align-items: stretch;
        gap: var(--margin-default);
      }

      div[oneline] {
        grid-column: span 12 / auto;

        display: flex;
        align-items: center;
        gap: var(--margin-default);
      }

      div[oneline] input {
        flex: 1;
      }

      div[oneline] select {
        flex: 1;
      }

      div[oneline] md-elevated-button {
        margin-bottom: var(--margin-default);
      }

      md-elevated-button[right] {
        margin-left: auto;
      }

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