import { Component, Input, OnInit, Output, EventEmitter, ChangeDetectorRef, AfterViewChecked, OnDestroy, OnChanges, SimpleChanges, ViewChild, AfterViewInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { GoalForActionService } from '../../../services/goalforaction.service';

import { GoalActionTemplateResolver } from '../../../resolvers/goal-template.resolver';
import { Subscription } from 'rxjs';
import { ActionService } from '../../../services/actions.service';
import { DynaDataSource } from '@xdf/gallery';
import { MatPaginator, MatSort } from '@angular/material';
import { Pagination, SortField } from '@xdf/commons';
import { GridActionService } from '../../../services/grid-action.service';
import { tap } from 'rxjs/operators';

@Component({
  selector: 'byte-goal-action-grid',
  templateUrl: './goal-action-grid.component.html',
  styleUrls: ['./goal-action-grid.component.scss']
})
export class GoalActionGridComponent implements OnInit,AfterViewChecked,OnDestroy,OnChanges,AfterViewInit {

  form: FormGroup;
  
  data: any[] = []

  actionsList = [];
  goalactionList=[];

  @Input() mode: string;
  currentmode: string;

  displayedColumns: string[] = ['id', 'identifier'];
  dataSource: DynaDataSource;
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort;
  sortColumn = 'id';
  sortDirection = 'asc';
  pagingSize = 5;
  @Output() onChange = new EventEmitter<boolean>();
  pagination: Pagination;

  changeFormSubscription: Subscription;
  constructor(
    private readonly changeDetectorRef: ChangeDetectorRef,
    protected goalForActionService: GoalForActionService,
    protected actionService: ActionService,
    protected gridService: GridActionService
  ) {
  }


  ngOnDestroy(): void {
    if (this.changeFormSubscription) {
      this.changeFormSubscription.unsubscribe;
    }
  }

  checkboxchange(){
    this.onChange.emit(true);
  }

ngOnInit() {
  this.currentmode=this.mode;
  this.actionsList = this.actionService.getActions();
  this.goalactionList = this.actionService.getGoalActions();
  this.form = this.getFields(this.mode);

  this.dataSource = new DynaDataSource(this.gridService);
    // Paginación
  this.pagination = new Pagination();

  this.pagination.currentPage = 0;
  this.pagination.itemsPerPage = this.pagingSize;

  this.pagination.totalItems = this.actionsList.length;

  if(this.actionsList.length%5==0) this.pagination.totalPages = this.actionsList.length/5
  else this.pagination.totalPages = Math.trunc(this.actionsList.length/5)+1 

  if (this.sortColumn && this.sortDirection) {
    this.pagination.sortFields = new Array();
    const sortField: SortField = new SortField();
    sortField.direction = this.sortDirection;
    sortField.field = this.sortColumn;
    this.pagination.sortFields.push(sortField);
  }
  this.dataSource.load(this.pagination);

  this.getChecked()

  if (this.form && this.mode !== 'view') {
    this.changeFormSubscription = this.form.valueChanges.subscribe(cambios => {  
      this.actionService.loadGoalActions(this.getDatachanges());    
    })
  }
}

getDatachanges():any{
  let cambios:any[] =[]
  for(let i=0;i<this.actionsList.length;i++){
    if(this.form.controls[this.actionsList[i]['identifier']].value){
      cambios.push({
        IdAction : (this.actionsList[i]['id']).toString()
      })
    }
  }

  return cambios
}

getChecked(){
  for(let i=0;i<this.actionsList.length;i++){
    for(let j=0;j<this.goalactionList.length;j++){
      if(this.actionsList[i]['id'].toString()==this.goalactionList[j]['IdAction']){
        this.form.controls[this.actionsList[i]['identifier']].setValue(true)
      }
      
    }
  }
}

public getFields(mode: string) {
  
  let validatorList = [];
  let form=new FormGroup({});
  if (mode !== 'new') {
    for(let i=0;i<this.actionsList.length;i++){
      form.addControl(this.actionsList[i]['identifier'],new FormControl({
        value:false,
        disabled: this.getDisabledMode(mode),
      }))
    }
  }
  else {
    for(let i=0;i<this.actionsList.length;i++){
      form.addControl(this.actionsList[i]['identifier'],new FormControl({
        value:false,
        disabled: this.getDisabledMode(mode),
      },validatorList))
    }
  }
  return form;
}

getDisabledMode(mode: string): boolean {
  return mode === 'view';
}

  
  ngOnChanges(cambios: SimpleChanges): void {
  if(this.currentmode!=this.mode && this.currentmode){
    this.form = this.getFields(this.mode);
    if(this.dataSource){
      this.dataSource.load(this.pagination);
    }
    this.getChecked()
    this.currentmode=this.mode
    
    if(this.mode=='new'){
      for(let i=0;i<this.actionsList.length;i++){
        this.form.controls[this.actionsList[i]['identifier']].setValue(false)
      }
    }
    if (this.form && this.mode !== 'view') {
      this.changeFormSubscription = this.form.valueChanges.subscribe(cambios => {   
        this.actionService.loadGoalActions(this.getDatachanges()); 
      });
    }
  }
  
}

pageChanged(event) {
  
  if (event.previousPageIndex > event.pageIndex) {
     // previous button clicked
  } else {
    // next button clicked
  }
}

disabledPopper(value: number): boolean {
  return value <= 30;
}

  


  ngAfterViewInit(): void{
    this.sort.sortChange.subscribe((res) => {
      if (!this.sort.disabled && this.sort.active) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection = this.sort.direction;
        sortField.field = this.sortColumn = this.sort.active;
        this.pagination.sortFields.push(sortField);
      }
      this.paginator.pageIndex = 0;
      this.dataSource.load(this.pagination);
    });

    this.paginator.page
      .pipe(
        tap(() => {
          this.pagination.currentPage = this.paginator.pageIndex;
          this.pagination.itemsPerPage = this.paginator.pageSize;
          this.dataSource.load(this.pagination);
        })
      )
      .subscribe();
      this.dataSource.load(this.pagination);
      //this.acciones=this.dataSource['data']
  }

  ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
  }
  



 }
