import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FormGroup, FormControl } from '@angular/forms';
import { Component, Inject, OnInit } from '@angular/core';

@Component({
  selector: 'app-order-filters',
  templateUrl: './order-filters.component.html',
  styleUrls: ['./order-filters.component.css']
})
export class OrderFiltersComponent implements OnInit {
  filtersGroup: FormGroup;
  progInitDate: Date | null;
  progFinaDate: Date | null;
  ejecInitDate: Date | null;
  ejecFinaDate: Date | null;

  regUsers: string[];
  users: Map<string, string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private data: any,
    private _dialogRef: MatDialogRef<OrderFiltersComponent>,
  ) { 
    this.progInitDate = null;
    this.progFinaDate = null;
    this.ejecInitDate = null;
    this.ejecFinaDate = null;

    this.regUsers = [];
    this.users = new Map();

    this.filtersGroup = new FormGroup({
      orderState: new FormControl(''),
      progInitDate: new FormControl(this.progInitDate),
      progFinaDate: new FormControl(this.progFinaDate),
      ejecInitDate: new FormControl(this.ejecInitDate),
      ejecFinaDate: new FormControl(this.ejecFinaDate),
      execUser: new FormControl('')
    });
  }

  ngOnInit(): void {
    let users: Map<string, string> = this.data.regUsers;
    this.regUsers = Array.from(users.keys());
    this.users = users;
  }

  applyFilters(){
    let filters = this.filtersGroup.getRawValue();
    let values = Object.values(filters);

    let valArr = [
      filters.orderState,
      filters.progInitDate == null ? null : `${filters.progInitDate.getFullYear()}-${filters.progInitDate.getMonth() + 1}-${filters.progInitDate.getDate()}`,
      filters.progFinaDate == null ? null : `${filters.progFinaDate.getFullYear()}-${filters.progFinaDate.getMonth() + 1}-${filters.progFinaDate.getDate()}`,
      filters.ejecInitDate == null ? null : `${filters.ejecInitDate.getFullYear()}-${filters.ejecInitDate.getMonth() + 1}-${filters.ejecInitDate.getDate()}`,
      filters.ejecFinaDate == null ? null : `${filters.ejecFinaDate.getFullYear()}-${filters.ejecFinaDate.getMonth() + 1}-${filters.ejecFinaDate.getDate()}`,
      filters.execUser 
    ];
    let valStr = JSON.stringify(valArr);
    
    this._dialogRef.close(valStr);
  }
}
