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 = [];
    }
    static { this.styles = [
        ButtonContainerStyles,
        css `
      :host {
        display: flex;
        flex-direction: column;

        border: 1px solid var(--md-sys-color-primary);
        font: normal 15px var(--theme-font);
      }

      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;
        color: var(--md-sys-color-secondary);
        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;
      }

      .category-group {
        display: contents;
      }

      .category-title {
        font-weight: bold;
        font-size: 0.9em;
        color: var(--md-sys-color-primary);
        text-transform: uppercase;
        opacity: 0.7;
        align-self: stretch;
        position: sticky;
        top: 0;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        text-align: right;
      }

      .category-privileges {
        display: contents;
      }

      @media screen and (min-width: 640px) {
        ul {
          grid-template-columns: minmax(200px, auto) 1fr 1fr;
          gap: 0;
        }

        .category-title {
          grid-column: 1;
          padding-right: var(--spacing-medium);
        }

        li {
          grid-column: auto;
        }
      }

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

      li {
        padding: var(--spacing-small);
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      }

      #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: 639px) {
        ul {
          grid-template-columns: 1fr;
        }

        .category-group {
          display: block;
          margin-top: var(--spacing-medium);
        }

        .category-group:first-child {
          margin-top: 0;
        }

        .category-title {
          position: static;
          margin-bottom: var(--spacing-small);
        }

        .category-privileges {
          display: grid;
          grid-template-columns: 1fr;
        }
      }
    `
    ]; }
    render() {
        const allPrivileges = this.allPrivileges || [];
        const privileges = this.privileges || [];
        const users = this.users || [];
        // Group privileges by category
        const groupedPrivileges = allPrivileges.reduce((acc, privilege) => {
            const category = privilege.category || 'Other';
            if (!acc[category]) {
                acc[category] = [];
            }
            acc[category].push(privilege);
            return acc;
        }, {});
        // Sort categories alphabetically
        const sortedCategories = Object.keys(groupedPrivileges).sort();
        // Sort privileges within each category by name (descending)
        sortedCategories.forEach(category => {
            groupedPrivileges[category].sort((a, b) => b.name.localeCompare(a.name));
        });
        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>
        ${sortedCategories.map(category => html `
            <div class="category-group">
              <div class="category-title">${category}</div>
              <div class="category-privileges">
                ${groupedPrivileges[category].map(
        /* privilege : {id, name, category, description} */
        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>
                  `)}
              </div>
            </div>
          `)}
      </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 => ({ id: e['data-privilege'].id }) // ObjectRef 타입에 맞게 id만 전송
        );
        const patch = { ...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
              category
              description
            }
            total
          }
        }
      `
        });
        return response.data.privileges.items;
    }
    async fetchPrivilegesOnRole(name) {
        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 = response.data.role?.privileges;
        this.users = response.data.role?.users;
    }
    showToast(message) {
        document.dispatchEvent(new CustomEvent('notify', { detail: { message, option: { timer: 1000 } } }));
    }
};
__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