import { __decorate, __metadata } from "tslib";
import '@operato/process/ox-process-modeller.js';
import './things-scene-components.import';
import gql from 'graphql-tag';
import { css, html } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { connect } from 'pwa-helpers/connect-mixin.js';
import { Model } from '@hatiolab/things-scene';
import { client, gqlContext } from '@operato/graphql';
import { OxPropertyEditor } from '@operato/property-editor';
import { PageView, store } from '@operato/shell';
import { OxProcessModeller } from '@operato/process/ox-process-modeller.js';
import { provider } from '../process-provider';
import components from './things-scene-components-with-tools.import';
const NOOP = () => { };
let ProcessModellerPage = class ProcessModellerPage extends connect(store)(PageView) {
    constructor() {
        super();
        this.processId = '';
        this.processName = '';
        this.model = {
            width: 1920,
            height: 1080
        };
        this.baseUrl = '';
        this.selected = [];
        this.mode = 1;
        this.hideProperty = false;
        this.overlay = '';
        this.scene = null;
        this.componentGroupList = OxProcessModeller.groups;
        this.fonts = [];
        this._showSpinner = false;
        this.process = null;
        components.forEach((component) => {
            OxProcessModeller.registerTemplate(component.templates);
        });
        /* 컴포넌트에서 정의된 에디터들을 MODELLER_EDITORS에 등록 */
        var addedEditors = {};
        for (let component in components) {
            let { editors } = components[component];
            editors &&
                editors.forEach((editor) => {
                    let { type, element } = editor;
                    addedEditors[type] = element;
                });
        }
        OxPropertyEditor.register(addedEditors);
    }
    get context() {
        return {
            title: this.process ? this.processName : this._showSpinner ? 'Fetching process...' : 'Process Not Found',
            help: 'process-modeller/modeller',
            widebleed: true
        };
    }
    get oopsNote() {
        return {
            icon: 'color_lens',
            title: 'EMPTY PROCESS',
            description: 'There are no process to be designed',
            click: NOOP
        };
    }
    async refresh() {
        var _a, _b;
        if (!this.processId) {
            this.process = null;
            this.model = {
                width: 1920,
                height: 1080
            };
            return;
        }
        try {
            this._showSpinner = true;
            this.updateContext();
            var response = await client.query({
                query: gql `
          query FetchProcessById($id: String!) {
            process(id: $id) {
              id
              name
              model
            }
          }
        `,
                variables: { id: this.processId },
                context: gqlContext()
            });
            var process = response.data.process;
            if (!process) {
                this.process = null;
                throw 'process not found';
            }
            this.process = Object.assign(Object.assign({}, process), { model: JSON.parse(process.model) });
            this.processName = (_a = this.process) === null || _a === void 0 ? void 0 : _a.name;
            this.model = Object.assign({}, (_b = this.process) === null || _b === void 0 ? void 0 : _b.model);
        }
        catch (ex) {
            document.dispatchEvent(new CustomEvent('notify', {
                detail: {
                    level: 'error',
                    message: ex,
                    ex
                }
            }));
        }
        finally {
            this._showSpinner = false;
            this.updateContext();
        }
    }
    updated(changes) {
        if (changes.has('processId')) {
            this.refresh();
        }
    }
    pageUpdated(changes, lifecycle) {
        var _a;
        if (this.active) {
            this.processId = lifecycle.resourceId;
        }
        else {
            this.processId = '';
            this.model = {
                width: 1280,
                height: 1020,
                components: []
            };
            (_a = this.modeller) === null || _a === void 0 ? void 0 : _a.close();
        }
    }
    stateChanged(state) {
        this.baseUrl = state.route.rootPath;
        this.fonts = state.font;
    }
    render() {
        var oops = (!this._showSpinner && !this.model && this.oopsNote);
        return oops
            ? html `
          <oops-note
            icon=${oops.icon}
            title=${oops.title}
            description=${oops.description}
            @click=${oops.click || NOOP}
          ></oops-note>
        `
            : html `
          <ox-process-modeller
            .mode=${this.mode}
            @mode-changed=${(e) => {
                this.mode = e.detail.value;
            }}
            .model=${this.model}
            @model-changed=${(e) => {
                this.model = e.detail.value;
            }}
            .scene=${this.scene}
            @scene-changed=${(e) => {
                this.scene = e.detail.value;
            }}
            .selected=${this.selected}
            @selected-changed=${(e) => {
                this.selected = e.detail.value;
            }}
            .baseUrl=${this.baseUrl}
            .provider=${provider}
            @save-model=${(e) => this.saveProcess()}
            .componentGroupList=${this.componentGroupList}
            .fonts=${this.fonts}
            .hideProperty=${this.hideProperty}
          >
          </ox-process-modeller>
          <oops-spinner ?show=${this._showSpinner}></oops-spinner>
        `;
        return html ``;
    }
    async updateProcess() {
        var _a;
        try {
            this._showSpinner = true;
            var { id, name, description, groupId } = this.process || {};
            var model = JSON.stringify((_a = this.scene) === null || _a === void 0 ? void 0 : _a.model);
            await client.mutate({
                mutation: gql `
          mutation UpdateProcess($id: String!, $patch: ProcessPatch!) {
            updateProcess(id: $id, patch: $patch) {
              id
            }
          }
        `,
                variables: {
                    id,
                    patch: { name, description, model, groupId }
                },
                context: gqlContext()
            });
            document.dispatchEvent(new CustomEvent('notify', {
                detail: {
                    level: 'info',
                    message: 'saved'
                }
            }));
        }
        catch (ex) {
            document.dispatchEvent(new CustomEvent('notify', {
                detail: {
                    level: 'error',
                    message: ex,
                    ex: ex
                }
            }));
        }
        finally {
            this._showSpinner = false;
        }
        this.updateContext();
    }
    async saveProcess() {
        await this.updateProcess();
    }
};
ProcessModellerPage.styles = [
    css `
      :host {
        display: flex;
        flex-direction: column;

        overflow: hidden;
        position: relative;
      }

      process-modeller {
        flex: 1;
      }

      oops-spinner {
        display: none;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }

      oops-spinner[show] {
        display: block;
      }

      oops-note {
        display: block;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    `
];
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], ProcessModellerPage.prototype, "processId", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], ProcessModellerPage.prototype, "processName", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Model)
], ProcessModellerPage.prototype, "model", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], ProcessModellerPage.prototype, "baseUrl", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], ProcessModellerPage.prototype, "selected", void 0);
__decorate([
    property({ type: Number }),
    __metadata("design:type", Number)
], ProcessModellerPage.prototype, "mode", void 0);
__decorate([
    property({ type: Boolean }),
    __metadata("design:type", Boolean)
], ProcessModellerPage.prototype, "hideProperty", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], ProcessModellerPage.prototype, "overlay", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], ProcessModellerPage.prototype, "scene", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Object)
], ProcessModellerPage.prototype, "componentGroupList", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], ProcessModellerPage.prototype, "fonts", void 0);
__decorate([
    property({ type: Boolean }),
    __metadata("design:type", Boolean)
], ProcessModellerPage.prototype, "_showSpinner", void 0);
__decorate([
    query('process-modeller'),
    __metadata("design:type", OxProcessModeller)
], ProcessModellerPage.prototype, "modeller", void 0);
ProcessModellerPage = __decorate([
    customElement('process-modeller-page'),
    __metadata("design:paramtypes", [])
], ProcessModellerPage);
export { ProcessModellerPage };
//# sourceMappingURL=process-modeller-page.js.map