import { Component, OnInit, Input, ViewContainerRef, ElementRef, ViewChild } from '@angular/core';
import { Subscription, of } from 'rxjs';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { MatStepper } 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';

export interface QuestionFile {
  idLoad: number;
  filename: string;
  status: string;
  user: string;
  dateLoad: string;
}

const ELEMENT_DATA: QuestionFile[] = [
  { idLoad: 1, filename: 'Questions-1.xlsx', status: 'LO', user: 'lortiz', dateLoad: '09-09-2020' },
  { idLoad: 2, filename: 'Questions-2.xlsx', status: 'LO', user: 'lortiz', dateLoad: '09-09-2020' },
  { idLoad: 3, filename: 'Questions-3.xlsx', status: 'LO', user: 'lortiz', dateLoad: '08-09-2020' },
  { idLoad: 4, filename: 'Questions-4.xlsx', status: 'AC', user: '', dateLoad: '' },
  { idLoad: 5, filename: 'Questions-5.xlsx', status: 'AC', user: '', dateLoad: '' },
  { idLoad: 6, filename: 'Questions-6.xlsx', status: 'AC', user: '', dateLoad: '' }
];

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


  displayedColumns: string[] = ['idLoad', 'filename', 'status', 'user', 'dateLoad', 'actions'];
  dataSource = ELEMENT_DATA;

  mapStatus = {
    "LO": {
      "text": "label.status.loaded",
      "class": "label label-primary"
    },
    "AC": {
      "text": "label.status.active",
      "class": "label label-info"
    }
  };

  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,
  ) {

    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(questions: any) {
    this.questions = questions;
    if (questions) {
      /*
      this.formGroup.patchValue({
        name: agentDetail.name,
        description: agentDetail.description
      });
      */
    }
  }

  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
        });
      }
    }
    /*
    this.files.forEach(file => {
      this.uploadFile(file);
    });
    */
  }

  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);
      }
    });
  }

  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();
    }
  }

}
