import { Component, OnInit, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
import { MdDialog, MdDialogRef, ComponentType } from '@angular/material';
import { TranslateService } from 'ng2-translate/ng2-translate';

import { UsersService } from '../shared/user/users.service';
import { UserDialogComponent } from '../shared/user';
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {

  rows = [];
  temp = [];
  count: number = 0;
  offset: number = 0;
  limit: number = 10;
  selectedRow: any;
  filters = {};

  @ViewChild('myTable') table: any;

  //columns: { name: string, cellTemplate?: TemplateRef<any>, frozenLeft?: boolean, width?: number }[];

  constructor(private translate: TranslateService,
    private userService: UsersService,
    private dialog: MdDialog,
    private viewContainerRef: ViewContainerRef) {
    let browserLang: string = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
  }

  ngOnInit() {

    this.page(this.offset, this.limit);

  }
  page(offset, limit) {
    this.userService.loadUsers().then(data => {
      this.temp = data;

      let userId = this.filters['userId'] ? this.filters['userId'].toString() : '';
      let firstName = this.filters['firstName'] ? this.filters['firstName'].toString() : '';
      let lastName = this.filters['lastName'] ? this.filters['lastName'].toString() : '';
      let email = this.filters['email'] ? this.filters['email'].toString() : '';
      let phone = this.filters['phone'] ? this.filters['phone'].toString() : '';
      let state = this.filters['state'] ? this.filters['state'].toString() : '';
      // filter our data
      const temp = this.temp.filter(function (d) {
        return (d['userId'].toString().toLowerCase().indexOf(userId) !== -1 || !userId) &&
          (d['firstName'].toString().toLowerCase().indexOf(firstName) !== -1 || !firstName) &&
          (d['lastName'].toString().toLowerCase().indexOf(lastName) !== -1 || !lastName) &&
          (d['email'].toString().toLowerCase().indexOf(email) !== -1 || !email) &&
          (d['phone'].toString().toLowerCase().indexOf(phone) !== -1 || !phone) &&
          ((!d['state'] && !state) || (d['state'] && d['state'].toString().toLowerCase().indexOf(state) !== -1) || !state);
      });

      this.rows = temp;
    });
  }

  onPage(event) {
    console.log('Page Event', event);
    this.page(event.offset, event.limit);
  }

  moreInfo(row: any): void {
    this.selectedRow = row;
    this.openUserDialog(UserDialogComponent);
  }

  toggleExpandRow(row) {
    console.log('Toggled Expand Row!', row);
    this.table.rowDetail.toggleExpandRow(row);
  }

  onDetailToggle(event) {
    console.log('Detail Toggled', event);
  }

  updateFilter(event, colName) {
    const val = event.target.value.toLowerCase();
    this.filters[colName] = val;
    let userId = this.filters['userId'] ? this.filters['userId'].toString() : '';
    let firstName = this.filters['firstName'] ? this.filters['firstName'].toString() : '';
    let lastName = this.filters['lastName'] ? this.filters['lastName'].toString() : '';
    let email = this.filters['email'] ? this.filters['email'].toString() : '';
    let phone = this.filters['phone'] ? this.filters['phone'].toString() : '';
    let state = this.filters['state'] ? this.filters['state'].toString() : '';
    // filter our data
    const temp = this.temp.filter(function (d) {
      return (d['userId'].toString().toLowerCase().indexOf(userId) !== -1 || !userId) &&
        (d['firstName'].toString().toLowerCase().indexOf(firstName) !== -1 || !firstName) &&
        (d['lastName'].toString().toLowerCase().indexOf(lastName) !== -1 || !lastName) &&
        (d['email'].toString().toLowerCase().indexOf(email) !== -1 || !email) &&
        (d['phone'].toString().toLowerCase().indexOf(phone) !== -1 || !phone) &&
        ((!d['state'] && !state) || (d['state'] && d['state'].toString().toLowerCase().indexOf(state) !== -1) || !state);
    });

    // update the rows
    this.rows = temp;
    // Whenever the filter changes, always go back to the first page
    this.table.offset = 0;
  }

  private openUserDialog(dialogType: ComponentType<{ user: any }>) {
    const closeByEventReason = 'request changed';
    let dialogRef = this.dialog.open(dialogType, {
      disableClose: false, width: '',
      height: '',
      position: {
        top: '',
        bottom: '',
        left: '',
        right: ''
      },
      viewContainerRef: this.viewContainerRef
    });
    dialogRef.componentInstance.user = this.selectedRow;
  }


}
