import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
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';
import { ValidatorUtils } from '@xdf/gallery';

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;

  @Output()
  nextPage: EventEmitter<boolean> = new EventEmitter<boolean>();

  agentDetail: any;
  formGroup: FormGroup;

  viewMode: boolean;
  mode = 'new';

  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,
    private validatorUtils: ValidatorUtils
  ) {

    this.mode = this.activatedRoute.snapshot.data.mode;
    this.viewMode = this.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 }),
      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 }),
      period: 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,
        period: agentDetail.period
      });

      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;
    // new field cq
    this.agentDetail.period = this.formGroup.controls.period.value;

    return true;
  }


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

  uploadFiles(event) {
    for (const i in event) {
      if (event[i] instanceof File) {
        const 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 {
          const message = 'label.imageAvatar.incompatible.extension';
          this.notificationService.showMessage(this.translateService.instant(message) +
            '[' + this.acceptedTypes + ']', null, NotificationType.error);
        }
      }
    }
  }

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

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

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

  next() {
    // debug cq
    // console.log(' agent period : ')
    // this.saveGeneralInformation(true);
    // console.log(this.agentDetail);
    // return;

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

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

  getErrors(name: string, placeholder: string) {
    return this.validatorUtils.getErrors(this.formGroup.controls[name] as FormControl, name, placeholder);
  }
}

