/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { SelectionModel } from '@angular/cdk/collections';
import { Component, Inject, Input, OnDestroy, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { BciFilterService, FilterTypes } from '@bci-web-core/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { UserService } from '../../../shared/user-service.service';
import { UserFilterService } from '../filter/user-filter.service';
import { FilterEntry, SelectionFilterEntry } from './complex-filter.model';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

/**
 * Component to show complex filters in modal dialog.
 */
@Component({
  selector: 'bci-complex-filter',
  templateUrl: './complex-filter.component.html',
  styleUrls: ['./complex-filter.component.scss'],
})
export class ComplexFilterComponent implements OnInit, OnDestroy {
  /** WARNING: This FilterEntry model does not work nicely in case multiple entries share a common state.
   *  POSSIBLE SOLUTION: Use a comprehensive filter state cloned from the commandbar's / tables filter state and sync it back upon closing the sidebar.
   *  ...and please consider contributing it back to the BCI Web Core ;)
   */

  filterDepartments = new SelectionFilterEntry(
    'Departments',
    this.userFilterService,
    this.userFilterService.departmentFilter,
    new SelectionModel<string>(true, this.userFilterService.departmentFilter.term, true)
  );
  filter1 = new FilterEntry('Filter 1', this.userFilterService, this.userFilterService.filter1);
  filter2 = new FilterEntry('Filter 2', this.userFilterService, this.userFilterService.filter2);
  filter3 = new FilterEntry('Filter 3', this.userFilterService, this.userFilterService.filter3);
  filter4 = new FilterEntry('Food', this.userFilterService, this.userFilterService.filter4);
  filters: FilterEntry[] = [this.filterDepartments, this.filter1, this.filter2, this.filter3, this.filter4];

  chosenFilter = this.filters[0];

  departments: string[] = [];
  showModal =false;

  foods = [
    { value: null, viewValue: 'None' },
    { value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' },
    { value: 'stationary', viewValue: 'Stationary' },
  ];


  //Changes for new Filter Component

  //Variable used for displaying old/new filter based on the input
  @Input() filterType: string;

  //holds the FilterTypes enum value
  filterTypes = FilterTypes;

  filterForm : FormGroup;

  ticketStatus = ['Open','In progress','Completed','Closed']

  private componentDestroyed$ = new Subject<void>();

  constructor(
    private userFilterService: UserFilterService,
    private userService: UserService,
    private dialogRef: MatDialogRef<ComplexFilterComponent, boolean>,
    private fb: FormBuilder,
    @Inject(MAT_DIALOG_DATA) public data: { filterType: FilterTypes },
    private bciFilterService: BciFilterService
  ) {
    this.filterType = data.filterType;
    this.filterForm = this.fb.group({
      ticketFilter: this.fb.group({
        creatorDetails: this.fb.group({
          username:  ['', Validators.minLength(3)],
          userRole: [''],
          unit: ['']
        }),
        ticketProgress: this.fb.group({
          progress: [0]
        }),
        ticketStatus: this.fb.group({
          status: ['']
        }),
      }),
      systemSettings: this.fb.group({
        compatibleDevices: this.fb.group({
          mobile: [false],
          tablet: [false],
          desktop: [false]
        }),
        systemAutoUpdates: this.fb.group({
          daily: [false],
          weekly: [false],
          monthly: [false],
          quarterly:[false]
        }),
        additionalFeatures: this.fb.group({
          feature: ['']
        })
      })
    })

    //Method to store the initial Form value, which will be used for reset functionality
    this.bciFilterService.setInitialFilterValues(this.filterForm);

    this.userService
      .queryDepartments()
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((departments) => {
        this.departments.length = 0;
        this.departments.push(...Array.from(departments));
        this.showModal = true;
      });
  }

  ngOnInit() {
    //The below logic is used to update the apply/reset button states based on the active count once the modal is open
    this.bciFilterService.activateApplyBtn = this.bciFilterService.activateResetAllBtn = false;
    if(this.bciFilterService.totalActiveFilterCount > 0) {
      this.filterForm.setValue(this.bciFilterService.nestedTabsFormGroup.value);
      this.bciFilterService.nestedTabsFormGroup = this.filterForm;
      this.bciFilterService.activateResetAllBtn = true;
    }
  }
  
  ngOnDestroy() {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }

  applyFilters() {
    if (this.filterType === FilterTypes.Old) {
      this.filters.forEach((filterEntry) => filterEntry.applyComplexFilter(this.userFilterService));
    } else {
      this.userFilterService.activateNewFilter();
    }
    this.dialogRef.close(true);
  }

  cancel() {
    this.dialogRef.close(false);
  }
}
