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;

  viewMode: boolean;

  allowDragAndDrop = false;

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

  countries = [
    {
      "name": "Perú",
      "timezones": [
        "GMT-5"
      ]
    },
    {
      "name": "Argentina",
      "timezones": [
        "GMT-3"
      ]
    },
    {
      "name": "Brazil",
      "timezones": [
        "GMT-5",
        "GMT-4",
        "GMT-3",
        "GMT-2"
      ]
    }
  ];

  timezones = [];

  languages = [
    {
      "name" : "Español"
    }
  ];

  types = [
    {
      "name" : "Agente de preguntas frecuentes"
    }
  ];

  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 }),
      country: new FormControl({ value: "", disabled: this.viewMode }),
      timezone: new FormControl({ value: "", disabled: this.viewMode }),
      language: new FormControl({ value: "", disabled: this.viewMode }),
      type: 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);
    }
  }

  onCountryChange(obj) {
    console.log('Country changed...');
    let selectedCountry = obj.value;
    console.log(selectedCountry);
    this.timezones = [];
    console.log(this.formGroup.controls['timezone'].value);
    this.formGroup.controls['timezone'].setValue(null);
    if (selectedCountry) {
      this.timezones = selectedCountry.timezones;
    } 
  }

  saveConnection(validateForm: boolean): boolean {
    if (validateForm && !this.formGroup.valid) {
      return false;
    }

    /*
    this.externalSystemDetail.abbreviation = this.formGroup.controls.abbreviation.value;
    this.externalSystemDetail.name = this.formGroup.controls.name.value;
    this.externalSystemDetail.description = this.formGroup.controls.description.value;
    this.externalSystemDetail.status = this.formGroup.controls.status.value ? 'AC' : 'IN';
    this.externalSystemDetail.inputType = this.formGroup.controls.inputType.value;
    this.externalSystemDetail.type = this.formGroup.controls.type.value;
    */
    return true;
  }


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

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



}

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

