import {
  AdvancedProperty,
  CheckBox,
  ComboBoxBase,
  DateTimePicker,
  FilterComponent,
  FilterGroup,
  TextBase,
} from "@webbpm/base-package";
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  Input
} from "@angular/core";
import {FilterTransferService} from "../../FilterTransferService";
import {FilterValuesTransferStrategy} from "../enum/FilterValuesTransferStrategy";

@Component({
             moduleId: module.id,
             selector: 'custom-filter-group',
             templateUrl: './../../../../../src/resources/template/ervu-dashboard/CustomFilterGroup.html',
             changeDetection: ChangeDetectionStrategy.OnPush
           })
export class CustomFilterGroup extends FilterGroup {
  private transferService: FilterTransferService;
  private filtersApplied: boolean = false;
  @Input()
  @AdvancedProperty()
  public filterValuesTransferStrategy: FilterValuesTransferStrategy;

  constructor(el: ElementRef, cd: ChangeDetectorRef) {
    super(el, cd);
  }

  public initialize() {
    super.initialize();
    this.transferService = this.injector.get(FilterTransferService);
    this.applySavedFilters();
  }

  public postStart(): void {
    if (this.liveFilter) {
      this.registerLiveFilteringFieldChangeListeners();
    }

    if (this.skipInitialLoading && !this.filtersApplied) {
      this.loadInitialValues();
      return;
    }

    this.progressIndicationService.showProgressBar();
    this.loadContainer()
        .then(() => {
          this.fireOnLoadEvent();
          this.progressIndicationService.hideProgressBar();
        })
        .catch((reason) => {
          console.error(
              `Failed to load container with id = ${this.getObjectId()}. Reason: ${reason.stack}`);

          this._isLoaded = false;
          this.progressIndicationService.hideProgressBar();
        });
  }

  private applySavedFilters(): void {
    const filters = this.transferService.getFilters();
    if (filters && Object.keys(filters).length > 0) {
      this.applyFilters(filters);
      this.transferService.clearFilters();
    }
  }

  private applyFilters(filters: any): void {
    const filterComponents: FilterComponent[] = this.getContainerComponents(FilterComponent);
    filterComponents.forEach(filter => {
      if (this.filterValuesTransferStrategy === FilterValuesTransferStrategy.BY_OBJECT_NAME) {
        const objectName = filter.getObjectName();
        const paramValue = filters[objectName];
        this.applyValueToControl(filter, paramValue);
      }
      else if (this.filterValuesTransferStrategy === FilterValuesTransferStrategy.BY_OBJECT_ID) {
        const objectId = filter.getObjectId();
        const paramValue = filters[objectId];
        this.applyValueToControl(filter, paramValue);
      }
    });
    this.filtersApplied = true;
  }

  private applyValueToControl(filter: FilterComponent, paramValue: any): void {
    if (paramValue) {
      const controlWithValue = filter.getControlWithValue();
      if (controlWithValue instanceof TextBase || controlWithValue instanceof ComboBoxBase) {
        controlWithValue.initialValue = paramValue;
      }
      else if (controlWithValue instanceof CheckBox) {
        controlWithValue.initialValue = paramValue.toLowerCase() === "true";
      }
      else if (controlWithValue instanceof DateTimePicker) {
        controlWithValue.initialValue = new Date(paramValue);
      }
    }
  }
}
