import { __decorate, __metadata } from "tslib";
import gql from 'graphql-tag';
import { css, html, LitElement } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { client, gqlContext } from '@operato/graphql';
import { i18next, localize } from '@operato/i18n';
import { OxPrompt } from '@operato/popup/ox-prompt.js';
import { ButtonContainerStyles } from '@operato/styles';
let RolePrivilegeEditor = class RolePrivilegeEditor extends localize(i18next)(LitElement) {
    constructor() {
        super(...arguments);
        this.allPrivileges = [];
        this.privileges = [];
        this.users = [];
    }
    render() {
        const allPrivileges = this.allPrivileges || [];
        const privileges = this.privileges || [];
        const users = this.users || [];
        return html `
      <div titler>${String(i18next.t('label.user'))}</div>

      <div users>${users.map(user => html `<div>${user.name} (${user.email})</div>`)}</div>

      <div titler>${String(i18next.t('field.privileges'))}</div>

      <div>
        <input id="checkAll" type="checkbox" @change=${e => this.oncheckAll(e)} />
        <label for="checkAll">Check all</label>
      </div>

      <ul privileges>
        ${allPrivileges.map(privilege => html `
            <li>
              <input
                type="checkbox"
                id="${privilege.id}"
                .checked=${privileges.map(p => p.id).indexOf(privilege.id) > -1}
                .data-privilege=${privilege}
              />
              <label for="${privilege.id}">${privilege.description}</label>
            </li>
          `)}
      </ul>

      <div class="button-container">
        <md-elevated-button @click=${e => this.onSave()}>${String(i18next.t('button.save'))}</md-elevated-button>
        <md-elevated-button @click=${e => this.onDeleteRole()} danger
          >${String(i18next.t('button.delete role'))}</md-elevated-button
        >
      </div>
    `;
    }
    async firstUpdated() {
        this.allPrivileges = await this.fetchPrivileges();
    }
    async updated(changes) {
        if (changes.has('role')) {
            await this.fetchPrivilegesOnRole(this.role.name);
        }
    }
    checkAll(checked) {
        Array.from(this.renderRoot.querySelectorAll('ul[privileges] input[type=checkbox]')).forEach(checkbox => (checkbox.checked = checked));
    }
    oncheckAll(e) {
        this.checkAll(e.target.checked);
    }
    async onSave() {
        const updateRoleObj = this.updateRoleObj;
        const privileges = Array.from(this.renderRoot.querySelectorAll('ul[privileges] input[type=checkbox]:checked')).map(e => e['data-privilege']);
        const patch = Object.assign(Object.assign({}, updateRoleObj), { privileges: privileges });
        if (this.role) {
            const response = await client.mutate({
                mutation: gql `
          mutation ($id: String!, $patch: RolePatch!) {
            updateRole(id: $id, patch: $patch) {
              id
              name
              description
              privileges {
                id
                description
              }
            }
          }
        `,
                variables: { id: this.role.id, patch },
                context: gqlContext()
            });
            if (!response.errors) {
                await this.dispatchEvent(new CustomEvent('fetch-roles'));
                this.showToast(i18next.t('text.data_updated_successfully'));
            }
        }
    }
    async onDeleteRole() {
        if (await OxPrompt.open({
            title: i18next.t('text.are_you_sure'),
            text: i18next.t('text.are_you_sure_to_delete_x', { x: i18next.t('label.role') }),
            confirmButton: { text: i18next.t('button.delete') },
            cancelButton: { text: i18next.t('button.cancel') }
        })) {
            const response = await client.mutate({
                mutation: gql `
          mutation ($id: String!) {
            deleteRole(id: $id)
          }
        `,
                variables: { id: this.role.id },
                context: gqlContext()
            });
            if (!response.errors) {
                await this.dispatchEvent(new CustomEvent('fetch-roles'));
                await OxPrompt.open({
                    type: 'success',
                    title: i18next.t('text.completed'),
                    text: i18next.t('text.x_deleted_successfully', { x: i18next.t('label.role') }),
                    confirmButton: { text: i18next.t('button.confirm') }
                });
            }
        }
    }
    async fetchPrivileges() {
        const response = await client.query({
            query: gql `
        query privileges {
          privileges {
            items {
              id
              name
              description
            }
            total
          }
        }
      `
        });
        return response.data.privileges.items;
    }
    async fetchPrivilegesOnRole(name) {
        var _a, _b;
        const response = await client.query({
            query: gql `
        query ($name: String!) {
          role(name: $name) {
            id
            name
            privileges {
              id
              description
            }
            users {
              name
              email
            }
          }
        }
      `,
            variables: { name },
            context: gqlContext()
        });
        this.privileges = (_a = response.data.role) === null || _a === void 0 ? void 0 : _a.privileges;
        this.users = (_b = response.data.role) === null || _b === void 0 ? void 0 : _b.users;
    }
    showToast(message) {
        document.dispatchEvent(new CustomEvent('notify', { detail: { message, option: { timer: 1000 } } }));
    }
};
RolePrivilegeEditor.styles = [
    ButtonContainerStyles,
    css `
      :host {
        display: flex;
        flex-direction: column;

        border: 1px solid var(--md-sys-color-primary);
        font: normal 15px var(--theme-font);
        color: var(--md-sys-color-secondary);
      }
      div {
        margin: var(--spacing-medium);
      }

      div[users] {
        margin: 0;
        background-color: var(--md-sys-color-surface-variant);
      }

      div[titler] {
        color: var(--md-sys-color-secondary);
        font: bold 1.2em var(--theme-font);
        text-transform: capitalize;
      }

      ul {
        flex: 1;
        background-color: var(--md-sys-color-surface-variant);
        overflow: auto;
        display: grid;
        grid-template-columns: 1fr 1fr;
        margin-block-start: 0;
        margin-block-end: 0;
        padding: var(--spacing-medium);
        list-style: none;
        border: 1px dashed rgba(0, 0, 0, 0.1);
        border-width: 1px 0;
      }

      input[type='checkbox'] {
        display: inline;
      }

      li {
        padding: var(--spacing-small);
      }

      #checkAll,
      [for='checkAll'] {
        margin-bottom: var(--spacing-medium);
        padding-bottom: var(--spacing-small);
        font-weight: bold;
      }

      md-elevated-button {
        margin: 5px;
        background-color: var(--md-sys-color-surface-variant);
      }

      md-outlined-button {
        background-color: var(--md-sys-color-surface-variant);
      }

      @media screen and (max-width: 480px) {
        ul {
          grid-template-columns: 1fr;
        }
      }
    `
];
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], RolePrivilegeEditor.prototype, "role", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], RolePrivilegeEditor.prototype, "allPrivileges", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], RolePrivilegeEditor.prototype, "updateRoleObj", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], RolePrivilegeEditor.prototype, "privileges", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], RolePrivilegeEditor.prototype, "users", void 0);
RolePrivilegeEditor = __decorate([
    customElement('role-privilege-editor')
], RolePrivilegeEditor);
//# sourceMappingURL=role-privilege-editor.js.map