import { DialogBoxViewModel } from './../../../modules/dialogs/dialog-box';
import { ColDef } from "ag-grid-community";
import { DialogCancellableOpenResult, DialogOpenResult } from "aurelia-dialog";
import { autoinject, useView } from "aurelia-framework";
import { Router } from "aurelia-router";
import { EntityTypeNames } from "../../../constants/constants";
import { ServiceBase } from "../../../data/service-base";
import { ActionDialogBoxInputParameters, FieldType, Role, Various } from "../../../model/common-model";
import { CustomLogger } from "../../../modules/custom-logger";
import { getSelectedColDef } from "../../list-view-is-selected-coldef";
import { ListViewModelBase } from "../../list-view-model-base";
import { KeyboardShortcut } from './../../../constants/constants';

@autoinject
@useView("./../../../vm/security/roles/role-list.html")
export class RoleList extends ListViewModelBase<Role> {
  public ressourceName: string = EntityTypeNames.Role;

  constructor(router: Router, logger: CustomLogger) {
    super(router, logger, new ServiceBase<Role>(EntityTypeNames.Role));
    this.canSelectAll = false;
  }

  public getDetailsUrl(self, entity: Role) {
    if (entity && entity.id) {
      return this.routePrefix + entity.id;
    }
    return null;
  }

  protected add() {
    this.navigateTo(this.routePrefix + Various.NewId);
  }

  private get routePrefix(): string {
    return this.router.routes.find(x => x.name == 'roles-detail').href.replace('' + Various.NewId, '');
  }

  public async delete(detachInverseFKEntities?: boolean) {
    if (this.selectedEntitiesCount != 1) {
      return;
    }
    return new Promise<boolean>(resolve => {
      let msg = this.i18n.tr('common:role.sureToDelete', { role: this.selectedEntities[0].name._translation ?? "" });
      // let buttonOk = this.i18n.tr("general.yes", { ns: "common" });
      let buttonDelete: ActionDialogBoxInputParameters =
      {
        label: this.i18n.tr("general.remove", { ns: "common" }),
        title: this.i18n.tr("general.remove", { ns: "common" }),
        theme: 'primary',
        type: 'solid',
        disabled: false,
        fn: (thisBox: DialogBoxViewModel) => {
          thisBox.controller.ok();
        },
        keyboardShortcut: this.config.globalConfig.keyboardShortcutFwBox ? KeyboardShortcut.Enter : null
      };
      let buttonCancel: ActionDialogBoxInputParameters =
      {
        label: this.i18n.tr("general.cancel", { ns: "common" }),
        title: this.i18n.tr("general.cancel", { ns: "common" }),
        theme: 'dark',
        type: 'ghost',
        disabled: false,
        fn: (thisBox: DialogBoxViewModel) => {
          thisBox.controller.cancel();
        },
        keyboardShortcut: this.config.globalConfig.keyboardShortcutFwBox ? [KeyboardShortcut.Escape, KeyboardShortcut.Backspace] : null
      };

      this.box.showQuestion(msg, this.i18n.tr("menu.question", { ns: "common" }), [buttonCancel, buttonDelete])
        .then((selectedOption: DialogCancellableOpenResult) => {
          (<DialogOpenResult>selectedOption).closeResult.then((result) => {
            if (!result.wasCancelled) {
              return this.service.deleteEntities(this.selectedEntities, detachInverseFKEntities, null, true).then(refresh => {
                if (refresh) {
                  this.refreshAfterDelete();
                }
              });
            } else {
              resolve(false);
            }
          });
        })
    });
  }

  protected isSelectable(entity: Role): boolean {
    return entity?.isLocked != true;
  }

  protected isSelectedChanged(entity: Role) {
    super.isSelectedChanged(entity);
    if ((entity as any)?.isSelected == false) {
      // If isSelected is false, this means we are in the process of selecting the row. Unselect all other rows
      this.getSelectableRows().forEach(entry => (entry as any).isSelected = entry.id == entity.id);
    }
  }

  protected duplicate() {
    if (this.selectedEntitiesCount != 1) {
      return;
    }
    this.router.navigateToRoute('roles-detail', { param1: Various.NewId, duplicateFrom: this.selectedEntities[0].id });
  }

  public getDataGridColumns() {
    let defs: ColDef[] = [
      getSelectedColDef(this),
      {
        headerName: this.i18n.tr('common:role.name', { ns: "common" }),
        field: "name._translation",
        type: FieldType.String,
        sort: 'asc'
      },
      {
        headerName: this.i18n.tr('common:role.description', { ns: "common" }),
        field: "description._translation",
        type: FieldType.String,
      },
      {
        headerName: this.i18n.tr('common:role.active', { ns: "common" }),
        field: "active",
        type: FieldType.Boolean,
      }
    ];
    return defs;
  }
}
