import { Component, OnInit, Input, ViewContainerRef, ElementRef, ViewChild } from '@angular/core';
import { Subscription, of } from 'rxjs';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { MatStepper, MatDialog } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { animate, trigger, state, transition, style } from '@angular/animations';
import { DomSanitizer } from '@angular/platform-browser';
import { AuthorizationService } from '@xdf/security';
import { TranslateService } from '@ngx-translate/core';
import { catchError, map } from 'rxjs/operators';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { UploadService } from '../upload.service';
import { CaFileUploadModalComponent } 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 {

  @Input() stepper: MatStepper;

  viewMode: boolean;

  questions: any;

  public resourceAuth = new Object();

  accept = '.xls,.xlsx';

  displayedColumns: string[] = ['id', 'filename', 'status', 'user', 'uploadDate', 'actions'];
  dataSource = [];

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

  files = [];

  constructor(protected route: ActivatedRoute,
    protected router: Router,
    protected vcRef: ViewContainerRef,
    protected authorizationService: AuthorizationService,
    private translate: TranslateService,
    private uploadService: UploadService,
    private formBuilder: FormBuilder,
    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 false;
  }

  buildForm(agentDetail: any) {
    this.dataSource = 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;
    */
  }

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

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

  uploadFiles(event) {
    for (const i in event) {
      if (event[i] instanceof File) {
        const reader = new FileReader();
        reader.onload = () => {
          //this.formGroup.controls['imageAvatar'].setValue(reader.result as string);
        };
        reader.readAsDataURL(event[i]);

        this.files.push({
          data: event[i],
          state: 'in',
          inProgress: false,
          progress: 0,
          canRetry: false
        });
      }
    }
  }

  uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file.data);

    file.inProgress = true;

    this.uploadService.upload(formData).pipe(
      map(event => {
        switch (event.type) {
          case HttpEventType.UploadProgress:
            file.progress = Math.round(event.loaded * 100 / event.total);
            break;
          case HttpEventType.Response:
            return event;
        }
      }),
      catchError((error: HttpErrorResponse) => {
        file.inProgress = false;
        return of(`${file.data.name} upload failed.`);
      })
    ).subscribe((event: any) => {
      if (typeof (event) === 'object') {
        console.log(event.body);
      }
    });
  }

  addFile() {
    let dialog = this.matDialog.open(CaFileUploadModalComponent, {
      width: '500px'
    });

    dialog.afterClosed().subscribe(result => {
      if (result) {
        //this.agentChannels.push({ ...result });
        //this.setStep(this.agentChannels.length - 1);
      }
    });
  }

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

    return success;
  }

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

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

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

}
