import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { AgentService } from '../../../service/agent.service';
import { MatDialogRef } from '@angular/material';
import { NotificationService, NotificationType } from '@xdf/commons';
import { TranslateService } from '@ngx-translate/core';

export class FileUploadModel {
  id: number;
  uuid: string;
  filename: string;
  status: string;
  user: string;
  uploadDate: string;
  description: string;

}
@Component({
  selector: 'byte-ca-file-upload-modal',
  templateUrl: './ca-file-upload-modal.component.html',
  styleUrls: ['./ca-file-upload-modal.component.scss']
})
export class CaFileUploadModalComponent implements OnInit {

  formGroup: FormGroup;

  accept = '.xls,.xlsx';

  fileInfo = new FileUploadModel();

  constructor(
    private formBuilder: FormBuilder,
    private agentService: AgentService,
    private _notificationService: NotificationService,
    private _translateService: TranslateService,
    public dialogRef: MatDialogRef<CaFileUploadModalComponent>
  ) {
    this.formGroup = this.formBuilder.group({
      description: new FormControl({ value: "", disabled: false }),
      file: new FormControl({ value: '', disabled: false })
    });
  }

  ngOnInit() {
  }

  uploadFile(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]);

        let fileSelected = {
          data: event[i],
          state: 'in',
          inProgress: false,
          progress: 0,
          canRetry: false
        }

        this.validateFile(fileSelected);
      }
    }
  }

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

    file.inProgress = true;

    this.agentService.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') {
        let info = event.body;
        this.fileInfo = new FileUploadModel();
        if (info) {
          let status = info.fileValidationResult.status;

          if ("OK" === status) {
            this.fileInfo.id = info.id;
            this.fileInfo.uuid = info.uuid;
            this.fileInfo.filename = info.fileName;
            this.fileInfo.status = info.status;
            this.fileInfo.user = info.user;
            this.fileInfo.uploadDate = info.uploadDate;

          } else if ("INCOMPATIBLE_EXTENSION" === status) {
            this.formGroup.controls.file.setValue(null);
            let message = "label.file.incompatible.extension";
            this._notificationService.showMessage(this._translateService.instant(message) + "[" + this.accept + "]", null, NotificationType.error);

          } else if ("CONTENT_ERROR" === status) {
            this.formGroup.controls.file.setValue(null);
            console.log(info.fileValidationResult);

          } else if ("HEADER_ERROR" === status) {
            this.formGroup.controls.file.setValue(null);
            console.log(info.fileValidationResult);
          }

        } else {
          this.formGroup.controls.file.setValue(null);
        }
      }
    });
  }

  ok() {
    this.fileInfo.description = this.formGroup.controls.description.value;
    this.dialogRef.close(this.fileInfo);
  }

}
