import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@operato/data-grist/ox-grist.js';
import '@operato/data-grist/ox-filters-form.js';
import '@operato/context/ox-context-page-toolbar.js';
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';
import { DataGrist } from '@operato/data-grist/ox-grist.js';
import { client } from '@operato/graphql';
import { i18next, localize } from '@operato/i18n';
import { notify } from '@operato/layout';
import { PageView, store } from '@operato/shell';
import { CommonHeaderStyles, CommonGristStyles, ScrollbarStyles } from '@operato/styles';
import { isMobileDevice } from '@operato/utils';
import { p13n } from '@operato/p13n';
import { OxPrompt } from '@operato/popup';
let EnvVarListPage = class EnvVarListPage extends connect(store)(p13n(localize(i18next)(PageView))) {
    constructor() {
        super(...arguments);
        this.active = false;
        this.mode = isMobileDevice() ? 'CARD' : 'GRID';
    }
    static { this.styles = [
        CommonGristStyles,
        CommonHeaderStyles,
        ScrollbarStyles,
        css `
      :host {
        display: flex;
        flex-direction: column;

        overflow: hidden;
      }

      ox-grist {
        overflow-y: auto;
        flex: 1;
      }
    `
    ]; }
    get context() {
        return {
            title: i18next.t('text.env-var-list-page'),
            search: {
                handler: (search) => {
                    this.grist.searchText = search;
                },
                value: this.grist?.searchText || ''
            },
            filter: {
                handler: () => {
                    this.grist.toggleHeadroom();
                }
            },
            actions: [
                {
                    title: i18next.t('button.save'),
                    action: this.onUpdateEnvVars.bind(this),
                    icon: 'save'
                },
                {
                    title: i18next.t('button.delete'),
                    action: this.onDeleteEnvVars.bind(this),
                    icon: 'delete'
                }
            ],
            toolbar: false
        };
    }
    render() {
        return html `
      <ox-grist
        .mode=${this.mode}
        .config=${this.config}
        .fetchHandler=${this.fetchHandler.bind(this)}
        .personalConfigProvider=${this.getPagePreferenceProvider('ox-grist')}
      >
        <div slot="headroom" class="header">
          <ox-context-page-toolbar class="actions" .context=${this.context}></ox-context-page-toolbar>
        </div>

        <ox-grist-personalizer slot="setting"></ox-grist-personalizer>
      </ox-grist>
    `;
    }
    async pageInitialized() {
        this.config = {
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'string',
                    name: 'name',
                    header: i18next.t('field.name'),
                    record: {
                        editable: true
                    },
                    filter: 'search',
                    sortable: true,
                    width: 320
                },
                {
                    type: 'string',
                    name: 'description',
                    header: i18next.t('field.description'),
                    record: {
                        editable: true
                    },
                    filter: 'search',
                    width: 460
                },
                {
                    type: 'checkbox',
                    name: 'active',
                    label: true,
                    header: i18next.t('field.active'),
                    record: {
                        editable: true
                    },
                    filter: true,
                    sortable: true,
                    width: 60
                },
                {
                    type: 'secret',
                    name: 'value',
                    header: i18next.t('field.value'),
                    record: {
                        editable: true
                    },
                    width: 640
                },
                {
                    type: 'datetime',
                    name: 'updatedAt',
                    header: i18next.t('field.updated_at'),
                    width: 180
                }
            ],
            rows: {
                appendable: true,
                selectable: {
                    multiple: true
                }
            },
            sorters: [
                {
                    name: 'name'
                }
            ]
        };
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            await this.updateComplete;
            this.grist.fetch();
        }
    }
    async fetchHandler({ page, limit, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          envVars(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              description
              value
              active
              updatedAt
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings
            }
        });
        return {
            total: response.data.envVars.total || 0,
            records: response.data.envVars.items || []
        };
    }
    async onUpdateEnvVars() {
        let patches = this.grist.dirtyRecords;
        if (patches && patches.length) {
            patches = patches.map(patch => {
                let patchField = patch.id ? { id: patch.id } : {};
                const dirtyFields = patch.__dirtyfields__;
                for (let key in dirtyFields) {
                    patchField[key] = dirtyFields[key].after;
                }
                patchField.cuFlag = patch.__dirty__;
                return {
                    ...patchField
                };
            });
            const response = await client.mutate({
                mutation: gql `
          mutation updateMultipleEnvVars($patches: [EnvVarPatch!]!) {
            updateMultipleEnvVars(patches: $patches) {
              name
            }
          }
        `,
                variables: { patches }
            });
            if (!response.errors) {
                this.grist.fetch();
                return this.showToast(i18next.t('text.updated_successfully'));
            }
        }
    }
    async onDeleteEnvVars() {
        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') }
        })) {
            const ids = this.grist.selected.map(record => record.id);
            if (ids && ids.length > 0) {
                const response = await client.mutate({
                    mutation: gql `
            mutation ($ids: [String!]!) {
              deleteEnvVars(ids: $ids)
            }
          `,
                    variables: {
                        ids
                    }
                });
                if (!response.errors) {
                    this.grist.fetch();
                    notify({
                        message: i18next.t('text.info_x_successfully', { x: i18next.t('text.delete') })
                    });
                }
            }
        }
    }
    showToast(message) {
        document.dispatchEvent(new CustomEvent('notify', { detail: { message } }));
    }
};
__decorate([
    property({ type: Boolean }),
    __metadata("design:type", Boolean)
], EnvVarListPage.prototype, "active", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], EnvVarListPage.prototype, "config", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EnvVarListPage.prototype, "mode", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], EnvVarListPage.prototype, "grist", void 0);
EnvVarListPage = __decorate([
    customElement('env-var-list-page')
], EnvVarListPage);
export { EnvVarListPage };
//# sourceMappingURL=env-var-list-page.js.map