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';
import { AgentService } from '../../../service/agent.service';
import { NotificationService, NotificationType } from '@xdf/commons';

@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;

  filestate=true;

  loadingOption = false;

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

  mapStatus = {
    OK: {
      class: 'label label-primary',
      text: 'label.status.loaded'
    },
    ER: {
      class: 'label label-danger',
      text: 'label.status.error'
    }
  };

  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,
    protected agentService: AgentService,
    private notificationService: NotificationService,
  ) {

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

  }

  ngOnInit() {
    const keyAuthorization = 'authorization';
    const authList = this.route.snapshot.paramMap[keyAuthorization];
    if(this.activatedRoute.snapshot.data.mode=='edit' && this.dataSource!=undefined){
      this.filestate=false;
    }

    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;
        if(result.status=="OK") this.filestate=false;
        else this.filestate=true;
      }
    });
  }

  onRetryRecord(element, index){
    this.loadingOption=true;
    this.agentService.retryData(element.uuid).subscribe((info=>{
      const listTemp = this.dataSource.data;
      //console.log(this.dataSource.data)
      let other=listTemp.splice(index, 1);
      const fileInfo = new FileUploadModel();
      fileInfo.id = info.id;
      fileInfo.description = other[0].description;
      fileInfo.uuid = info.uuid;
      fileInfo.filename = info.fileName;
      fileInfo.status = info.status;
      fileInfo.user = info.user;
      fileInfo.uploadDate = info.uploadDate;
      this.loadingOption=false;
      if(info.status=="OK"){
        this.filestate=false;
        this.agentService.loadfileData(fileInfo)
      } 
      else {
        this.filestate=true;

        const title = this.translate.instant('title.information');
        const message = this.translate.instant(info.message);
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.error);
        
      }
      listTemp.push(fileInfo);
      this.dataSource.data = listTemp;
    }), error=>{
      this.notificationService.showMessage(this.translate.instant('NO.KNOWLEDGE.FOUND'), undefined, NotificationType.error);
      //this.notificationService.showMessage('No se establecio conexion con el knowledge', '', NotificationType.error);
      console.log(error)
      this.loadingOption=false;
    })
  }

  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) {
    this.loadingOption=true;
    if(this.activatedRoute.snapshot.data.mode=='create'){
      this.agentService.deleteFile(item.uuid).subscribe((res=>{
        if(res['message']=='OK'){
          const listTemp = this.dataSource.data;
          listTemp.splice(index, 1);
          this.dataSource.data = listTemp;
          this.dirty = true;
          this.loadingOption=false;
        }else{
          const title = this.translate.instant('title.information');
          const message = this.translate.instant('CANNOT.DELETE');
              this.notificationService.showMessage(
              message,
              title,
              NotificationType.error
               );
          this.loadingOption=false;
          this.dirty = true;
        }
      }),error=>{
        this.loadingOption=false;
      }
      );
    }
    else{
      const listTemp = this.dataSource.data;
      listTemp.splice(index, 1);
      this.agentService.addDeletedFile(item);
      this.dataSource.data = listTemp;
      this.dirty = true;
      this.loadingOption=false;
    }
    // this.agentService.deleteFile(item.uuid).subscribe(res=>{
     
    //   const listTemp = this.dataSource.data;
    //   listTemp.splice(index, 1);
    //   this.dataSource.data = listTemp;
    //   this.dirty = true;
    //   this.loadingOption=false;
    // });
  }

  next() {
    // cq
    this.stepper.next();
      return;
      
    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();
    }
  }

}
