import { Component, OnInit, Input, ViewContainerRef, ViewChild, Output } from '@angular/core';
import { AfterViewInit, EventEmitter } from '@angular/core';
import { MatStepper, MatDialog, MatTableDataSource, MatSort } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { animate, trigger, state, transition, style } from '@angular/animations';
import { AuthorizationService } from '@xdf/security';
import { TranslateService } from '@ngx-translate/core';
import { CaFileUploadModalComponent, FileUploadModel } from '../ca-file-upload-modal/ca-file-upload-modal.component';

@Component({
  selector: 'byte-ca-frequent-questions',
  templateUrl: './ca-frequent-questions.component.html',
  styleUrls: ['./ca-frequent-questions.component.scss'],
  animations: [
    trigger('fadeInOut', [
      state('in', style({ opacity: 100 })),
      transition('* => void', [
        animate(300, style({ opacity: 0 }))
      ])
    ])
  ]
})
export class CaFrequentQuestionsComponent implements OnInit, AfterViewInit {

  @ViewChild(MatSort, { static: false }) sort: MatSort;

  @Input()
  stepper: MatStepper;

  @Output()
  nextPage: EventEmitter<boolean> = new EventEmitter<boolean>();

  public resourceAuth = new Object();
  dirty = false;



  accept = '.xls,.xlsx';
  agentDetail: any;
  displayedColumns: string[] = ['id', 'filename', 'description', 'status', 'user', 'uploadDate', 'actions'];
  dataSource = new MatTableDataSource<FileUploadModel>([]);

  mapStatus = {
    LO: {
      class: 'label label-primary',
      text: 'label.status.loaded'
    },
    PS: {
      class: 'label label-warning',
      text: 'label.status.pending'
    }
  };

  files = [];
  viewMode: boolean;

  constructor(
    protected route: ActivatedRoute,
    protected router: Router,
    protected vcRef: ViewContainerRef,
    protected authorizationService: AuthorizationService,
    private translate: TranslateService,
    private activatedRoute: ActivatedRoute,
    private matDialog: MatDialog
  ) {

    this.viewMode = this.activatedRoute.snapshot.data.mode === 'view';

  }

  ngOnInit() {
    const keyAuthorization = 'authorization';
    const authList = this.route.snapshot.paramMap[keyAuthorization];
    if (authList) {
      this.resourceAuth = new Object();
      authList.forEach(option => {
        this.resourceAuth[option] = true;
      });
    }

  }

  isDirty() {
    return this.dirty;
  }

  buildForm(agentDetail: any) {
    this.agentDetail = agentDetail;

    if (agentDetail.frequentQuestions) {
      this.dataSource.data = agentDetail.frequentQuestions;
    }
  }

  setDataForWizard(result: any) {
    console.log(result);
    /*
    this.protocols = result.connectionProtocolOptions;
    this.generalProperties = result.generalProperties;
    this.alias = result.alias;
    this.maxNumberOfConnectionsByExternalSystem = result.maxNumberOfConnectionsByExternalSystem;
    this.columnsForEntity = result.columnsForEntity;
    */
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

  getClassStatus(status) {
    return this.mapStatus[status].class;
  }

  getTextStatus(status) {
    return this.translate.instant(this.mapStatus[status].text);
  }

  addFile() {
    const dialog = this.matDialog.open(CaFileUploadModalComponent, {
      width: '600px',
      data: null
    });

    dialog.afterClosed().subscribe(result => {
      if (result) {
        const fileAdded = { ...result };
        const listTemp = this.dataSource.data;
        listTemp.push(fileAdded);
        this.dataSource.data = listTemp;
        this.dirty = true;
      }
    });
  }

  onEditRecord(item, index) {
    item.editable = true;

    const dialog = this.matDialog.open(CaFileUploadModalComponent, {
      width: '500px',
      data: item
    });

    dialog.afterClosed().subscribe(result => {
      if (result) {
        const fileEdited = { ...result };

        const listTemp = this.dataSource.data;
        listTemp[index] = fileEdited;

        this.dataSource.data = listTemp;
      }
    });
  }

  saveQuestions(validateForm: boolean) {
    const success = true;

    this.agentDetail.frequentQuestions = this.dataSource.data;

    return success;
  }

  onDeleteRecord(item, index) {
    const listTemp = this.dataSource.data;
    listTemp.splice(index, 1);
    this.dataSource.data = listTemp;
    this.dirty = true;
  }

  next() {
    if (!this.dataSource.data.length) {
      return;
    }

    if (this.viewMode) {
      this.stepper.next();
      return;
    }

    if (this.saveQuestions(true)) {
      this.nextPage.emit(this.isDirty());
      this.stepper.next();
    }
  }

}
