import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  OnChanges,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ChangeDetectorRef
} from '@angular/core';
import {BaseList} from '../../../../../../core/base/base-list';
import {SelectionModel} from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import { Location } from '@angular/common';

@Component({
  selector: 'app-create-exam-suject-table',
  templateUrl: './create-exam-suject-table.component.html',
  styleUrls: ['./create-exam-suject-table.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CreateExamSujectTableComponent extends BaseList implements OnInit , OnChanges {
  @Input() dataSource2: any = [];
  @Input() dataSource: any = [];
  @Input() SubjectGetCheck: any = [];
  column = ['1', '2', '3'];
  selection = new SelectionModel(true, []);
  uncheckedData:any = [];
  @Output() SubjectChecked = new EventEmitter();
  @Output() save = new EventEmitter();
  @Input() testingInfoData: any;
  checkedData = [];
  checkedDataSource = new MatTableDataSource(this.checkedData);
  checkedSelection = new SelectionModel(true, []);

  selectedRows = [];
  selectedRowsChecked = [];

  @ViewChild('paginator') paginator: MatPaginator;
  @ViewChild('checkedpaginator') checkedpaginator: MatPaginator;
  constructor(
    private cdRef: ChangeDetectorRef,
    private location: Location
  ) {
    super();
  }

  ngOnInit(): void {
     // this.uncheckedData = this.dataSource;
  }

  ngOnChanges() {
    // console.log(this.dataSource)
    // this.uncheckedData = this.dataSource;
    console.log(this.dataSource2);
    if (this.dataSource2 !== null){
      this.uncheckedData = this.dataSource2
      this.dataSource = this.updateMatTable(this.dataSource2 ? this.dataSource2 : []);
      const DatatableLength = this.dataSource.data;
      if (DatatableLength.length !== 0 && this.SubjectChecked.length != 0){
        for (const option of this.SubjectGetCheck) {
          // const exists = DatatableLength.find((x) => x.subject_uid === option.subject_uid);
          const exists = Array.isArray(DatatableLength) ? DatatableLength.find((x) => x.subject_uid === option.subject_uid) : 0;
          if (exists !== 0){
            this.selection.toggle(exists);
            this.transferSelectedRows();
          }
        }
      }
      this.checkedDataSource.paginator = this.checkedpaginator;
    }

  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  isAllCheckedSelected() {
    const numSelected = this.checkedSelection.selected.length;
    const numRows = this.checkedDataSource.data.length;
    return numSelected === numRows;
  }


  transferSelectedRows() {
    console.log( this.selection.selected);
    this.selection.selected.forEach(item => {
      console.log(item.subject_uid)
      console.log(this.uncheckedData)
      this.uncheckedData.map( (d,index) => {
        if (item.subject_uid === d.subject_uid){
          this.checkedData.push(this.uncheckedData[index]);
          this.uncheckedData.splice(index,1);
        }
      })
    });
    this.selection = new SelectionModel(true, []);
    this.dataSource = new MatTableDataSource(this.uncheckedData);
    this.checkedDataSource = new MatTableDataSource(this.checkedData);
    this.dataSource.paginator = this.paginator;
    this.checkedDataSource.paginator = this.checkedpaginator;
    this.sendDataback(this.checkedData);
    this.isAllSelected();
  }


  removeSelectedRows() {
    this.checkedSelection.selected.forEach(item => {
      const index: number = this.checkedData.findIndex(d => d === item);
      this.uncheckedData.push(this.checkedData[index]);
      this.checkedData.splice(index,1);
    });

    this.checkedSelection = new SelectionModel(true, []);
    this.dataSource = new MatTableDataSource(this.uncheckedData);
    this.checkedDataSource = new MatTableDataSource(this.checkedData);
    this.dataSource.paginator = this.paginator;
    this.checkedDataSource.paginator = this.checkedpaginator;
    this.sendDataback(this.checkedData);
    this.isAllCheckedSelected();
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    if (this.dataSource.filter != null || this.dataSource.filter != ''){
      this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.filteredData.forEach(row => this.selection.select(row));
    }else {
      this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
    }
  }

  masterCheckedToggle() {
    if (this.dataSource.filter != null || this.dataSource.filter != ''){
      this.isAllSelected() ?
        this.checkedSelection.clear() :
        this.checkedDataSource.filteredData.forEach(row => this.checkedSelection.select(row));
    }else {
      this.isAllSelected() ?
        this.checkedSelection.clear() :
        this.checkedDataSource.data.forEach(row => this.checkedSelection.select(row));
    }
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  applyFilter2(event: Event) {
    const filterValue2 = (event.target as HTMLInputElement).value;
    this.checkedDataSource.filter = filterValue2.trim().toLowerCase();
  }

  sendDataback(datasend){
    this.SubjectChecked.emit(datasend);
  }

  saveSend(){
    this.save.emit();
  }

  back(){
    this.location.back()
  }

}
