import { Router } from 'aurelia-router';
import { autoinject, Container, useView } from 'aurelia-framework';
import { ColDef } from 'ag-grid-community';
import moment from 'moment';
import { EnumerationType, FieldType, User, Various } from '../../../model/common-model';
import { EntityTypeNames, RolesMode } from "../../../constants/constants";
import { ListViewModelBase } from '../../list-view-model-base';
import { CustomLogger } from '../../../modules/custom-logger';
import { ServiceBase } from '../../../data/service-base';
import { getSelectedColDef } from '../../../vm/list-view-is-selected-coldef';
import { EnumerationTypeService } from '../../../services/enumeration-type-service';

@autoinject
// @useView("./../../../vm/security/users/user-list.html")
export abstract class UserListBase<T extends User> extends ListViewModelBase<T> {
  public ressourceName: string = EntityTypeNames.User;

  protected languageCategory: number | null = null;

  private languages: Array<EnumerationType> = [];

  constructor(protected rolesMode: RolesMode, ressourceName: string = EntityTypeNames.User) {
    super(Container.instance.get(Router), Container.instance.get(CustomLogger), new ServiceBase<T>(ressourceName));
    this.ressourceName = ressourceName;
    this.service.gridDataSource.expands = ['roles.role'];
    // Required to correctly apply rolesMode to column definitions
    this.initializeGridOptions();
  }

  public async activate(params: any) {
    await super.activate(params);
    if (this.languageCategory != null) {
      this.languages = await new EnumerationTypeService(this.languageCategory).getAll();
      this.initializeGridOptions();
    }
  }


  public getDetailsUrl(self, entity: T) {
    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 == 'users-detail').href.replace('' + Various.NewId, '');
  }

  public getDataGridColumns() {
    let defs = [];
    if (this.rolesMode != 'none') {
      defs.push(
        {
          headerName: this.i18n.tr("role.roles", { ns: 'common' }),
          field: "roles.role.name._translation",
          cellRenderer: 'manyToManyTagRenderer',
          type: FieldType.ManyToMany,
          floatingFilterComponentParams: {
            suppressFilterButton: true,
            serviceName: EntityTypeNames.Role,
          },
          filterParams: {
            serviceName: EntityTypeNames.Role,
          }
        }
      );
    }
    defs.push(...[
      getSelectedColDef(this),
      {
        headerName: this.i18n.tr(`user.${this.authService.usernameType}`, { ns: 'common' }),
        field: "username",
        type: FieldType.String,
        sort: 'asc'
      },
      {
        headerName: this.i18n.tr("user.lastName", { ns: 'common' }),
        field: "lastName",
        type: FieldType.String,
        sort: 'asc'
      },
      {
        headerName: this.i18n.tr("user.firstName", { ns: 'common' }),
        field: "firstName",
        type: FieldType.String,
        sort: 'asc'
      },
      {
        headerName: this.i18n.tr("user.disabled", { ns: 'common' }),
        field: "disabled",
        type: FieldType.Boolean
      },
      {
        headerName: this.i18n.tr("general.createdTime", { ns: 'common' }),
        field: "createdTime",
        hide: true,
        valueFormatter: data => data?.value == null ? '' : moment(data.value).format(Various.DateFormatWithHours),
        type: FieldType.DateTime
      },
      {
        headerName: this.i18n.tr("general.updatedTime", { ns: 'common' }),
        field: "updatedTime",
        hide: true,
        valueFormatter: data => data?.value == null ? '' : moment(data.value).format(Various.DateFormatWithHours),
        type: FieldType.DateTime
      },
      {
        headerName: this.i18n.tr("general.createdByFullName", { ns: 'common' }),
        field: "createdByFullName",
        hide: true,
        type: FieldType.User,
        floatingFilterComponentParams: {
          suppressFilterButton: true,
          userServiceName: this.ressourceName,
        },
        filterParams: {
          userServiceName: this.ressourceName,
        }
      },
      {
        headerName: this.i18n.tr("general.updatedByFullName", { ns: 'common' }),
        field: "updatedByFullName",
        hide: true,
        type: FieldType.User,
        floatingFilterComponentParams: {
          suppressFilterButton: true,
          userServiceName: this.ressourceName,
        },
        filterParams: {
          userServiceName: this.ressourceName,
        }
      }
    ]);

    // if (this.languageCategory != null) {
    //   defs.push(
    //     {
    //       headerName: this.i18n.tr("user.language", { ns: 'common' }),
    //       field: "languageCode",
    //       valueFormatter: (data) => {
    //         return data.value == null ? "" : this.languages.find(x => x.uniqueCode.toLowerCase() == data.value.toLowerCase()).denomination._translation;
    //       },
    //       type: FieldType.String
    //     }
    //   );
    // }
    return defs;
  }
}
