import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@material/web/button/elevated-button.js';
import '@operato/data-grist/ox-grist.js';
import '@operato/data-grist/ox-filters-form.js';
import '@operato/data-grist/ox-record-creator.js';
import { CommonButtonStyles, CommonHeaderStyles, CommonGristStyles, ScrollbarStyles } from '@operato/styles';
import { PageView, store } from '@operato/shell';
import { css, html } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { DataGrist } from '@operato/data-grist';
import { client } from '@operato/graphql';
import { i18next, localize } from '@operato/i18n';
import { notify } from '@operato/layout';
import { OxPrompt } from '@operato/popup';
import { isMobileDevice } from '@operato/utils';
import { connect } from 'pwa-helpers/connect-mixin';
import gql from 'graphql-tag';
let DomainLinkLManagement = class DomainLinkLManagement extends connect(store)(localize(i18next)(PageView)) {
    constructor() {
        super(...arguments);
        this.mode = isMobileDevice() ? 'CARD' : 'GRID';
    }
    static { this.styles = [
        ScrollbarStyles,
        CommonGristStyles,
        CommonHeaderStyles,
        css `
      :host {
        display: flex;

        width: 100%;

        --grid-record-emphasized-background-color: #8b0000;
        --grid-record-emphasized-color: #ff6b6b;
      }

      ox-grist {
        overflow-y: auto;
        flex: 1;
      }

      ox-filters-form {
        flex: 1;
      }
    `
    ]; }
    get context() {
        return {
            title: i18next.t('title.domain-link management'),
            search: {
                handler: (search) => {
                    this.grist.searchText = search;
                },
                value: this.grist.searchText
            },
            filter: {
                handler: () => {
                    this.grist.toggleHeadroom();
                }
            },
            help: 'auth/domain-link',
            actions: [
                {
                    title: i18next.t('button.save'),
                    action: this.updateDomainLink.bind(this),
                    ...CommonButtonStyles.save
                },
                {
                    title: i18next.t('button.delete'),
                    action: this.deleteDomainLink.bind(this),
                    ...CommonButtonStyles.delete
                }
            ]
        };
    }
    render() {
        const mode = this.mode || (isMobileDevice() ? 'CARD' : 'GRID');
        return html `
      <ox-grist .mode=${mode} .config=${this.gristConfig} .fetchHandler=${this.fetchHandler.bind(this)}>
        <div slot="headroom" class="header">
          <div class="filters">
            <ox-filters-form autofocus without-search></ox-filters-form>

            <div id="modes">
              <md-icon @click=${() => (this.mode = 'GRID')} ?active=${mode == 'GRID'}>grid_on</md-icon>
              <md-icon @click=${() => (this.mode = 'LIST')} ?active=${mode == 'LIST'}>format_list_bulleted</md-icon>
              <md-icon @click=${() => (this.mode = 'CARD')} ?active=${mode == 'CARD'}>apps</md-icon>
            </div>

            <ox-record-creator id="add" .callback=${this.creationCallback.bind(this)}>
              <button>
                <md-icon>add</md-icon>
              </button>
            </ox-record-creator>
          </div>
        </div>
      </ox-grist>
    `;
    }
    async pageInitialized(lifecycle) {
        this.gristConfig = {
            list: {
                fields: ['sourceDomain', 'targetDomain'],
                details: ['type', 'updatedAt']
            },
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'resource-object',
                    name: 'sourceDomain',
                    header: i18next.t('field.source-domain'),
                    record: {
                        editable: true,
                        mandatory: true,
                        options: {
                            title: i18next.t('title.lookup domains'),
                            queryName: 'domains'
                        }
                    },
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'select',
                    name: 'type',
                    header: i18next.t('field.type'),
                    record: {
                        editable: true,
                        mandatory: true,
                        options: () => ['', 'has', 'maintains', 'owns']
                    },
                    filter: 'search',
                    width: 200
                },
                {
                    type: 'resource-object',
                    name: 'targetDomain',
                    header: i18next.t('field.target-domain'),
                    record: {
                        editable: true,
                        mandatory: true,
                        options: {
                            title: i18next.t('title.lookup domains'),
                            queryName: 'domains'
                        }
                    },
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'resource-object',
                    name: 'updater',
                    header: i18next.t('field.updater'),
                    record: {
                        editable: false
                    },
                    sortable: true,
                    width: 120
                },
                {
                    type: 'datetime',
                    name: 'updatedAt',
                    header: i18next.t('field.updated_at'),
                    record: {
                        editable: false
                    },
                    sortable: true,
                    width: 180
                }
            ],
            rows: {
                appendable: false,
                selectable: {
                    multiple: true
                }
            },
            sorters: [
                {
                    name: 'sourceDomain'
                }
            ]
        };
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            // do something here when this page just became as active
        }
    }
    async fetchHandler({ page = 1, limit = 100, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: domainLinks(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              sourceDomain {
                id
                name
                subdomain
              }
              targetDomain {
                id
                name
                subdomain
              }
              type
              updater {
                id
                name
              }
              updatedAt
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings
            }
        });
        return {
            total: response.data.responses.total || 0,
            records: response.data.responses.items || []
        };
    }
    async deleteDomainLink() {
        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!]!) {
              deleteDomainLinks(ids: $ids)
            }
          `,
                    variables: {
                        ids
                    }
                });
                if (!response.errors) {
                    this.grist.fetch();
                    notify({
                        message: i18next.t('text.info_x_successfully', { x: i18next.t('text.delete') })
                    });
                }
            }
        }
    }
    async updateDomainLink() {
        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 ($patches: [DomainLinkPatch!]!) {
            updateMultipleDomainLink(patches: $patches) {
              sourceDomain {
                id
                name
                subdomain
              }
              targetDomain {
                id
                name
                subdomain
              }
              type
            }
          }
        `,
                variables: {
                    patches
                }
            });
            if (!response.errors) {
                this.grist.fetch();
            }
        }
    }
    async creationCallback(domainLink) {
        try {
            const { sourceDomain, targetDomain, type } = domainLink;
            if (!sourceDomain || !targetDomain || !type) {
                throw new Error(i18next.t('text.please_fill_all_required_fields'));
            }
            if (domainLink.sourceDomain.id === domainLink.targetDomain.id) {
                throw new Error(i18next.t('text.source_and_target_domain_cannot_be_same'));
            }
            const response = await client.query({
                query: gql `
          mutation ($domainLink: NewDomainLink!) {
            createDomainLink(domainLink: $domainLink) {
              id
            }
          }
        `,
                variables: {
                    domainLink
                },
                context: {
                    hasUpload: true
                }
            });
            if (!response.errors) {
                this.grist.fetch();
                document.dispatchEvent(new CustomEvent('notify', {
                    detail: {
                        message: i18next.t('text.data_created_successfully')
                    }
                }));
            }
            return true;
        }
        catch (ex) {
            console.error(ex);
            document.dispatchEvent(new CustomEvent('notify', {
                detail: {
                    type: 'error',
                    message: ex.message || String(ex)
                }
            }));
            return false;
        }
    }
};
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], DomainLinkLManagement.prototype, "gristConfig", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], DomainLinkLManagement.prototype, "mode", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], DomainLinkLManagement.prototype, "grist", void 0);
DomainLinkLManagement = __decorate([
    customElement('domain-link-management')
], DomainLinkLManagement);
export { DomainLinkLManagement };
//# sourceMappingURL=domain-link-management.js.map