import { Component, OnInit, Input, ViewContainerRef } from '@angular/core';
import { Subscription, of } from 'rxjs';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { MatStepper } from '@angular/material';
import { ActivatedRoute } from '@angular/router';
import { animate, trigger, state, transition, style } from '@angular/animations';
import { DomSanitizer } from '@angular/platform-browser';

export const FILE_TYPE = {
  image: /image.*/,
  file: /.*/
};
@Component({
  selector: 'byte-ca-general-information',
  templateUrl: './ca-general-information.component.html',
  styleUrls: ['./ca-general-information.component.scss'],
  animations: [
    trigger('fadeInOut', [
      state('in', style({ opacity: 100 })),
      transition('* => void', [
        animate(300, style({ opacity: 0 }))
      ])
    ])
  ]
})
export class CaGeneralInformationComponent implements OnInit {

  @Input() stepper: MatStepper;

  agentDetail: any;
  formGroup: FormGroup;

  types: any;
  viewMode: boolean;

  allowDragAndDrop = false;

  files: Array<FileUploadModel> = [];
  type = 'image';
  imageName = "imageAvatar";
  //urlBase = './service/file/download/';
  urlBase = '';

  constructor(
    private formBuilder: FormBuilder,
    private _activatedRoute: ActivatedRoute,
    private domSanitizer: DomSanitizer
  ) {

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

    this.formGroup = this.formBuilder.group({
      name: new FormControl({ value: "", disabled: this.viewMode }),
      description: new FormControl({ value: "", disabled: this.viewMode }),
      version: new FormControl({ value: "", disabled: this.viewMode }),
      imageAvatar: new FormControl({ value: "", disabled: this.viewMode })
    });

  }

  ngOnInit() {
  }

  buildForm(agentDetail: any) {
    this.agentDetail = agentDetail;
    if (agentDetail) {
      this.formGroup.patchValue({
        name: agentDetail.name,
        description: agentDetail.description
      });
    }
  }


  isDirty() {
    return this.formGroup.dirty;
  }

  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]);
        console.log("Imagen cargada");
        /*
        this.files.push({
          data: event[i], state: 'in',
          inProgress: false, progress: 0, canRetry: false, canCancel: true
        });
        */
      }
    }
    /*
    this.files.forEach(file => {
      this.sendFile(file);
    });
    */
  }

  cancelFile(file: FileUploadModel) {
    file.sub.unsubscribe();
    this.removeFileFromArray(file);
  }

  /*
  private sendFile(file: FileUploadModel) {
    const fd = new FormData();
    fd.append(this.param, file.data);

    const req = new HttpRequest('POST', this.target, fd, {
      reportProgress: true
    });

    file.inProgress = true;
    file.sub = this._http.request(req).pipe(
      map(event => {
        switch (event.type) {
          case HttpEventType.UploadProgress:
            file.progress = Math.round(event.loaded * 100 / event.total);
            break;
          case HttpEventType.Response:
            return event;
        }
      }),
      tap(message => { }),
      last(),
      catchError((error: HttpErrorResponse) => {
        file.inProgress = false;
        file.canRetry = true;
        return of(`${file.data.name} upload failed.`);
      })
    ).subscribe(
      (event: any) => {
        if (typeof (event) === 'object') {
          this.updateFormControlValue(event.body);
          this.removeFileFromArray(file);
          this.completed.emit(event.body);
        }
      }
    );
  }
  */

  private removeFileFromArray(file: FileUploadModel) {
    const index = this.files.indexOf(file);
    if (index > -1) {
      this.files.splice(index, 1);
    }
  }

}

export class FileUploadModel {
  data: File;
  state: string;
  inProgress: boolean;
  progress: number;
  canRetry: boolean;
  canCancel: boolean;
  sub?: Subscription;
}

