import { Injectable } from '@angular/core';
import { cnst_LoadedEntitiesExpiresInMs, EN_AppEntities, EN_AppPages, EN_HttpQueriesCount4Page } from '@app_consts';
import { CoreUser } from '@app_core/models/coreuser';
import { RepositoryService } from '@app_core/services/http/repository.service';
import { CorePageService } from '@app_core/services/page.service';
import { Department, DepartmentFilter } from '@app_models/basedata/department';
import { DocumentArtToDepartment } from '@app_models/documentart-to-department';
import { Employee } from '@app_models/employee';
import { User } from '@app_models/user';
import { WindreamIndex } from '@app_models/windream-index';
import { WindreamIndexToWindreamSearchToDepartment } from '@app_models/windream-index-to-windream-search-to-department';
import { ClientIdFilter, WindreamSearch } from '@app_models/windream-search';
import { WindreamSearchItem } from '@app_models/windream-search-item';
import { WindreamSearchItemToWindreamSearchToDepartment } from '@app_models/windream-search-item-to-windream-search-to-department';
import { WindreamSearchToDepartment, WindreamSearchToDepartmentFilter } from '@app_models/windream-search-to-department';
import { AppBaseEntityWrapper } from '@app_services/app.baseentity.wrapper';
import { AppBaseEntityListWrapper } from '@app_services/app.baseentitylist.wrapper';


@Injectable({ providedIn: 'root' })

export class DepartmentDataService extends CorePageService {
  protected appPage: EN_AppPages = EN_AppPages.Department;
  protected loadImedeately: boolean = true; //load on pening the page
  protected get appPageNoQueries() { return EN_HttpQueriesCount4Page.Department; }

  // --- running data
  departmentFilter: DepartmentFilter = new DepartmentFilter('DepartmentFullFilter');
  departmentList: AppBaseEntityListWrapper<Department> = new AppBaseEntityListWrapper<Department>(Department, 'Abteilungsliste', EN_AppEntities.Department);

  departmentDetails: AppBaseEntityWrapper<Department>;
  windreamSearchToDepartmentDetails: AppBaseEntityWrapper<WindreamSearchToDepartment>;
  // tslint:disable-next-line: max-line-length
  windreamSearchToDepartmentList: AppBaseEntityListWrapper<WindreamSearchToDepartment> = new AppBaseEntityListWrapper<WindreamSearchToDepartment>(WindreamSearchToDepartment, 'Windream Suche Kacheln', EN_AppEntities.WindreamSearchToDepartment);
  windreamSearchToDepartmentFilter: WindreamSearchToDepartmentFilter = new WindreamSearchToDepartmentFilter('DepartmentFilter');
  // tslint:disable-next-line: max-line-length
  windreamSearchItemToWindreamSearchToDepartmentList: AppBaseEntityListWrapper<WindreamSearchItemToWindreamSearchToDepartment> = new AppBaseEntityListWrapper<WindreamSearchItemToWindreamSearchToDepartment>(WindreamSearchItemToWindreamSearchToDepartment, 'Windream Suchbausteine', EN_AppEntities.WindreamSearchItemToWindreamSearchToDepartment);
  windreamSearchItemToWindreamSearchToDepartmentFilter: WindreamSearchToDepartmentFilter = new WindreamSearchToDepartmentFilter('WindreamSearchToDepartmentFilter');
  windreamSearchItemToWindreamSearchToDepartmentDetails: AppBaseEntityWrapper<WindreamSearchItemToWindreamSearchToDepartment>;

  windreamSearchItemList: AppBaseEntityListWrapper<WindreamSearchItem> = new AppBaseEntityListWrapper<WindreamSearchItem>(WindreamSearchItem, 'windream suche kacheln attribute', EN_AppEntities.WindreamSearchItem);
  windreamIndexToWindreamSearchToDepartmentDetails: AppBaseEntityWrapper<WindreamIndexToWindreamSearchToDepartment>;
  // tslint:disable-next-line: max-line-length
  windreamIndexToWindreamSearchToDepartmentList: AppBaseEntityListWrapper<WindreamIndexToWindreamSearchToDepartment> = new AppBaseEntityListWrapper<WindreamIndexToWindreamSearchToDepartment>(WindreamIndexToWindreamSearchToDepartment, 'Ausgabespalten für Windream Suche', EN_AppEntities.WindreamIndexToWindreamSearchToDepartment);
  windreamIndexToWindreamSearchToDepartmentFilter: WindreamSearchToDepartmentFilter = new WindreamSearchToDepartmentFilter('WindreamSearchToDepartmentFilter');

  windreamSearchList: AppBaseEntityListWrapper<WindreamSearch> =
    new AppBaseEntityListWrapper<WindreamSearch>(WindreamSearch, 'Windream Suche Kacheln', EN_AppEntities.WindreamSearch);

  clientIdFilter: ClientIdFilter = new ClientIdFilter('ClientIdFilter');

  windreamIndexList: AppBaseEntityListWrapper<WindreamIndex> =
    new AppBaseEntityListWrapper<WindreamIndex>(WindreamIndex, 'Windream Index', EN_AppEntities.WindreamIndex);

  documentArtToDepartmentListFilter: DepartmentFilter = new DepartmentFilter('DepartmentFilter');

  documentArtToDepartmentList: AppBaseEntityListWrapper<DocumentArtToDepartment> =
    new AppBaseEntityListWrapper<DocumentArtToDepartment>(DocumentArtToDepartment, 'Dokumentartenliste für Department', EN_AppEntities.DocumentArtToDepartment);

  employeeList: AppBaseEntityListWrapper<Employee> = new AppBaseEntityListWrapper<Employee>(Employee, 'mitarbeiter', EN_AppEntities.Employee + '/all');

  selectedDocumentarts: number[] = [];
  clpbrdWindreamOutColHint1: string;
  clpbrdWindreamOutColHints: string;
  clpbrdWindreamOutColList: WindreamIndexToWindreamSearchToDepartment[] = [];

  clpbrdWindreamSearchItemHint1: string;
  clpbrdWindreamSearchItemHints: string;
  clpbrdWindreamSearchItemList: WindreamSearchItemToWindreamSearchToDepartment[] = [];

  constructor(
    private repositoryService: RepositoryService,
  ) {
    super();

    this.departmentList.focusedCallBack = this.focusCallBack.bind(this);
    this.departmentList.filter = this.departmentFilter;
    this.departmentDetails = this.departmentList.createFocusedShadowEntity(AppBaseEntityWrapper.EN_ViewMode);
    this.departmentDetails.loadedDataExpiresInMs = cnst_LoadedEntitiesExpiresInMs;
    this.baseEntityWrapperWaitLoading = this.departmentDetails;
    this.activateRouting4EntityList(this.departmentList); //we are using routing

    this.windreamSearchToDepartmentList.filter = this.windreamSearchToDepartmentFilter;
    this.windreamSearchToDepartmentDetails = this.windreamSearchToDepartmentList.createFocusedShadowEntity();
    this.windreamSearchToDepartmentDetails.dontLoadEntity = true;
    this.windreamSearchToDepartmentDetails.beforeNewCallBack = this.prepareSearchToDepartment.bind(this);

    this.windreamIndexToWindreamSearchToDepartmentList.filter = this.windreamIndexToWindreamSearchToDepartmentFilter;
    this.windreamIndexToWindreamSearchToDepartmentDetails = this.windreamIndexToWindreamSearchToDepartmentList.createFocusedShadowEntity();
    this.windreamIndexToWindreamSearchToDepartmentDetails.dontLoadEntity = true;

    this.windreamSearchItemToWindreamSearchToDepartmentList.filter = this.windreamSearchItemToWindreamSearchToDepartmentFilter;
    this.windreamSearchItemToWindreamSearchToDepartmentDetails = this.windreamSearchItemToWindreamSearchToDepartmentList.createFocusedShadowEntity();
    this.windreamSearchItemToWindreamSearchToDepartmentDetails.dontLoadEntity = true;

    this.windreamSearchList.filter = this.clientIdFilter;
    this.windreamIndexList.filter = this.clientIdFilter;
    this.windreamSearchItemList.filter = this.clientIdFilter;
    this.documentArtToDepartmentList.filter = this.documentArtToDepartmentListFilter;


    this.departmentDetails.detailItems.register(this.windreamSearchToDepartmentList, null, 'departmentId');
    this.departmentDetails.detailItems.register(this.documentArtToDepartmentList, null, 'departmentId', (docarts: DocumentArtToDepartment[]) => {
      this.selectedDocumentarts = docarts.map(docart => docart.documentArtId);
    });
    this.windreamSearchToDepartmentDetails.detailItems.register(this.windreamIndexToWindreamSearchToDepartmentList, null, 'windreamSearchToDepartmentId');
    this.windreamSearchToDepartmentDetails.detailItems.register(this.windreamSearchItemToWindreamSearchToDepartmentList, null, 'windreamSearchToDepartmentId');

    this.loadBaseData();
    this.init();
  }


  loadData() {
    super.loadData();
    this.departmentList.load(null, null, () => this.pageLoadingService.updatePageLoadedCounters(this.appPage));
  }

  public loadBaseData() {
    super.loadBaseData(this.appPage, 1);
    this.employeeList.load(null, null, () => this.pageLoadingService.updatePageLoadedCounters(this.appPage));
  }

  public focusCallBack(focusedItem: Department) {
    this.clientIdFilter.clientId = focusedItem?.clientId;
  }

  public clearData() {
    super.clearData();
    this.departmentFilter.filterReset();
    this.departmentList.clear();
  }

  protected onLoggedInOut(user: CoreUser) {
    this.userChanged(new User(user));
    super.onLoggedInOut(user);
  }

  private userChanged(user: User) {
    if (this.authService.isLoggedIn()) {
      this.departmentDetails.canNew = user.isMaster;
      this.departmentDetails.canEdit = this.departmentDetails.canNew;
      this.departmentDetails.canDelete = this.departmentDetails.canNew;
    }
  }

  moveUpDown(direction: number,
    list:
        AppBaseEntityListWrapper<WindreamSearchToDepartment>
      | AppBaseEntityListWrapper<WindreamSearchItemToWindreamSearchToDepartment>
      | AppBaseEntityListWrapper<WindreamIndexToWindreamSearchToDepartment>
  ) {
    const curItemIndex: number = list.focusedItemIndex;
    if (!(direction < 0 && curItemIndex === 0 || direction > 0 && curItemIndex === list.items.length)) {
      const targetItem = list.items[curItemIndex + direction];
      const targetSeq: number = targetItem.seq;
      const currentItem = list.focusedItem;
      targetItem.seq = currentItem.seq;
      currentItem.seq = targetSeq;
      targetItem.entityChanged = true;
      currentItem.entityChanged = true;

      targetItem.save(this.repositoryService, null, null, null);
      currentItem.save(this.repositoryService, null, null, null);
      this.sortBySeq(list.items);
    }
  }

  public sortBySeq(list: WindreamSearchToDepartment[] | WindreamSearchItemToWindreamSearchToDepartment[] | WindreamIndexToWindreamSearchToDepartment[]) {
    list.sort((fp1, fp2) => (fp1.seq - fp2.seq));
  }


  prepareSearchToDepartment(item: WindreamSearchToDepartment) {
    const maxSeq = this.windreamSearchToDepartmentList.items.reduce<number>((max: number, _index: WindreamSearchToDepartment) => max > _index.seq ? max : _index.seq, 0);
    item.seq = maxSeq + 1;
    item.isActive = true;
  }


}
