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

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

  constructor(
    private formBuilder: FormBuilder,
    private agentService: AgentService
  ) {
    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') {
        console.log(event.body);
      }
    });
  }

}
