import { Component, OnInit, Input, ViewContainerRef } from '@angular/core';
import { Subscription, of } from 'rxjs';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material';
import { ActivatedRoute } from '@angular/router';
import { animate, trigger, state, transition, style } from '@angular/animations';
import { NotificationService, NotificationType } from '@xdf/commons';
import { TranslateService } from '@ngx-translate/core';

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;

  imageName = "imageAvatar";
  urlBase = '';

  countries = [];
  timezones = [];

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

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

  acceptedImageTypes = ['image/png', 'image/jpeg', 'image/gif'];
  acceptedTypes = "PNG, JPEG, GIF";

  constructor(
    private formBuilder: FormBuilder,
    private _activatedRoute: ActivatedRoute,
    private _notificationService: NotificationService,
    private _translateService: TranslateService
  ) {

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

    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 }, { validators: [Validators.required] }),
      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,
        version: agentDetail.version,
        timezone: agentDetail.timezone,
        country: agentDetail.countryId,
        imageAvatar: agentDetail.avatar,
        language: agentDetail.language,
        type: agentDetail.type
      });

      this.onCountryChange(this.formGroup.controls.country);
    }
  }

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

    this.agentDetail.name = this.formGroup.controls.name.value;
    this.agentDetail.description = this.formGroup.controls.description.value;
    this.agentDetail.version = this.formGroup.controls.version.value;
    this.agentDetail.countryId = this.formGroup.controls.country.value;
    this.agentDetail.timezone = this.formGroup.controls.timezone.value;
    this.agentDetail.avatar = this.formGroup.controls.imageAvatar.value;
    this.agentDetail.language = this.formGroup.controls.language.value;
    this.agentDetail.type = this.formGroup.controls.type.value;

    return true;
  }


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

  uploadFiles(event) {
    for (const i in event) {
      if (event[i] instanceof File) {
        let eventTemp = event[i];

        if (this.acceptedImageTypes.includes(eventTemp.type)) {

          const reader = new FileReader();
          reader.onload = () => {
            this.formGroup.controls['imageAvatar'].setValue(reader.result as string);
          };
          reader.readAsDataURL(event[i]);
        } else {
          let message = "label.imageAvatar.incompatible.extension";
          this._notificationService.showMessage(this._translateService.instant(message) + "[" + this.acceptedTypes + "]", null, NotificationType.error);
        }
      }
    }
  }

  onCountryChange(obj, deleteTimeZone?: boolean) {
    let selectedCountry = obj.value;
    this.timezones = [];

    if (deleteTimeZone) {
      this.formGroup.controls['timezone'].setValue(null);
    }

    if (selectedCountry) {
      for (var index in this.countries) {
        if (selectedCountry === this.countries[index].id) {
          this.timezones = this.countries[index].timezones;
          break;
        }
      }
    }
  }

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

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

