import { EntityDetailViewModelBase } from "../detail-view-model-base";
import { Country, Locality, Various } from "../../model/common-model";
import { autoinject, computedFrom } from "aurelia-framework";
import { Router } from "aurelia-router";
import { CustomLogger } from "../../modules/custom-logger";
import { EditingModeEnum } from "../editing-mode-enum";
import { ServiceBase } from "../../data/service-base";
import { FilterQueryOp, Predicate } from "breeze-client";
import { EntityTypeNames } from "../../constants/constants";

@autoinject
export class LocalityDetail extends EntityDetailViewModelBase<Locality>{
  @computedFrom("entity", "isCreationMode")
  public get documentTitle() {
    if (this.isCreationMode) {
      return this.i18n.tr("common:locality.addLocality");
    }
    return this.entity.name._translation;
  }
  public ressourceName = "";

  public countryService: ServiceBase<Country>;

  public communeService: ServiceBase<Locality>;
  /**
   *
   */
  constructor(router: Router, logger: CustomLogger) {
    super(router, logger);
    this.countryService = new ServiceBase<Country>(EntityTypeNames.Country);
    this.communeService = new ServiceBase<Locality>(EntityTypeNames.Locality);
    super.initialize(new ServiceBase<Locality>(EntityTypeNames.Locality));

  }


  public async activate(params: any): Promise<void> {
    await super.activate(params);
    let id = params.param1;
    if (id == Various.NewId) {
      this.editingMode = EditingModeEnum.Create;
      this.entity = await this.service.createEntity();
    } else {
      this.editingMode = EditingModeEnum.Update;
      this.entity = await this.service.getEntityById(id, 'country', 'commune');
    }

    this.initCustomSelect2Predicate();
  }
  initCustomSelect2Predicate() {
    this.communeService.gridDataSource.customSelect2Predicates = () => {
      let pSubCommune = new Predicate("isSubCommune", FilterQueryOp.NotEquals, "true");
      if (this.isCreationMode) {
        return pSubCommune;
      }
      return pSubCommune.and(new Predicate('id', FilterQueryOp.NotEquals, this.entity.id));
    }
  }

}