import { MdbTablePaginationComponent, MdbTableDirective, MDBModalService } from 'angular-bootstrap-md';

import { Component, OnInit, ViewChild, HostListener, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { ScenariosService } from '../services/scenarios.service';
import { ScenarioModalComponent } from '../modals/edit-scenario.component';

@Component({
  selector: 'table-scenarios',
  templateUrl: './table-scenarios.component.html',
  styleUrls: ['./table-scenarios.component.scss']
})
export class TableScenariosComponent implements OnInit, AfterViewInit {
  
  @ViewChild(MdbTablePaginationComponent, { static: true }) mdbTablePagination: MdbTablePaginationComponent;
  @ViewChild(MdbTableDirective, { static: true }) mdbTable: MdbTableDirective;
  
  previous: any = [];
  searchText: string = '';
  maxVisibleItems: number = 25;
  totalCount: number = 0;

  currentUser;
  scenarios;
  editField: string;

  elements = [];

  @HostListener('input') oninput() {
    this.mdbTablePagination.searchText = this.searchText;
  }

  constructor(private modalService: MDBModalService, private cdRef: ChangeDetectorRef, private _scenariosService: ScenariosService) {   
  }

  private _initElements(): void {
    this.mdbTable.setDataSource(this.elements);
    this.elements = this.mdbTable.getDataSource();
    this.previous = this.mdbTable.getDataSource();
  }

  private _refresh() {
    var scenariosSub = this._scenariosService.getScenariosAll().subscribe( res => {
        scenariosSub.unsubscribe();  
        this.totalCount = res.total;
        this.scenarios = res.results;
        this.elements = res.results;
        this._initElements();
       
    });
  }

  ngOnInit() {
    this._refresh();
  }

  ngAfterViewInit() {
    this.mdbTablePagination.setMaxVisibleItemsNumberTo(this.maxVisibleItems);

    this.mdbTablePagination.calculateFirstItemIndex();
    this.mdbTablePagination.calculateLastItemIndex();
    this.cdRef.detectChanges();
  }

  searchItems() {
    const prev = this.mdbTable.getDataSource();

    if (!this.searchText) {
      this.mdbTable.setDataSource(this.previous);
      this.elements = this.mdbTable.getDataSource();
    }

    if (this.searchText) {
      this.elements = this.mdbTable.searchLocalDataBy(this.searchText);
      this.mdbTable.setDataSource(prev);
    }

    this.mdbTablePagination.calculateFirstItemIndex();
    this.mdbTablePagination.calculateLastItemIndex();

    this.mdbTable.searchDataObservable(this.searchText).subscribe(() => {
      this.mdbTablePagination.calculateFirstItemIndex();
      this.mdbTablePagination.calculateLastItemIndex();
    });
  }

  changeValue(scenario: any, property: string, event: any) {
    this.editField = event.target.textContent;
    //console.log("changeValue editField", id, this.editField);
  }


  updateList(scenario: any, property: string, event: any) {
    this.editField = event.target.textContent;
    let patch = {};
    patch[property] = this.editField.trim();

    if (!patch[property] || patch[property] === "" || patch[property] === scenario[property] ) {
        return;
    }
    this._scenariosService.updateScenario(scenario._id.toString(), patch).subscribe( res=> {
        console.log("done", res);
        this._refresh();
    });
  }

  updateJson(scenario: any, property: string, event: any) {
    this.editField = event.target.textContent.trim();

    try {
        var patch = {};
        var value = JSON.parse(this.editField);

        if ( JSON.stringify(value) === JSON.stringify(scenario[property]) ) {
            return;
        }

        patch[property] = value;
        console.log("editField", patch);

        this._scenariosService.updateScenario(scenario._id.toString(), patch).subscribe( res=> {
            console.log("done", res);
            this._refresh();
        });
    } catch (e) {
        console.log("error json", e);
        this._refresh();
    }
    
  }

  FieldsChange(scenario: any,property: string, value:any){
    let patch = {};
    patch[property] = value.checked;
    this._scenariosService.updateScenario(scenario._id.toString(), patch).subscribe( res=> {
        console.log("done", res);
        this._refresh();
    });
  }

  openNewScenarioModal(scenario) {
    var modalRef = this.modalService.show(ScenarioModalComponent, {
      class: 'modal-lg modal-notify',
      containerClass: '',
      data: {
        scenario: scenario
      }
    } );

    var sub = modalRef.content.action.subscribe( (data: any) => { 
      sub.unsubscribe();
      
      console.log("new scenario data", data);
      this._refresh();
    });
  }

}