import { Component, OnInit } from '@angular/core';
import { NavService, Menu } from '../../../../services/nav.service';
import { TranslateService } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { LanguageService } from '../../../../services/language.service';

@Component({
  selector: 'app-languages',
  templateUrl: './languages.component.html',
  styleUrls: ['./languages.component.scss']
})
export class LanguagesComponent implements OnInit {

  public language: boolean = false;
  public selectedLanguage: any;
  public alertMessage: any
  // public languages: any[];
  public languages: any[] = [{
    language: 'English',
    code: 'en',

  }]
  // {
  //   language: 'Hindi',
  //   code: 'hi',
  //   // icon: 'HI'
  // },]

  // public selectedLanguage: any = {
  //   language: 'English',
  //   code: 'en',
  //   type: 'US',
  //   icon: 'us'
  // }

  constructor(
    public navServices: NavService,
    private languageService: LanguageService,
    private toastrService: ToastrService
  ) { }

  async ngOnInit() {
    await this.getLanguages();
    let lang = localStorage.getItem("selectedLanguage")!;;
    this.selectedLanguage = lang ? lang : 'en';
  }

  changeLanguage(lang: { code: any; }) {
    this.selectedLanguage = lang.code;
    localStorage.setItem("selectedLanguage", this.selectedLanguage);
    window.location.reload();
  }

  public async getLanguages() {
    try {

      let res = await this.languageService.getLanguage(null, null);
      if (res && res.status == 200) {
        if (res.recordList && res.recordList.length > 0) {
          this.languages = res.recordList.filter((c: any) => c.isActive == true);
          this.languages = [...this.languages]
        }
      }
    } catch (error: any) {
      this.alertMessage = error;
      if (error?.message!) {
        this.alertMessage = error.message
      }
      if (error?.error && error.error.message) {
        this.alertMessage = error.error.message
      }
      if (error?.error && error.error.error && error.error.error.functionErrorMessage) {
        this.alertMessage = error.error.error.functionErrorMessage
      }
      this.toastrService.error(this.alertMessage)
    }
  }
}
