import { MainStateManager } from './MainStateManager';
import { GetAllFactory } from './Language/GetAll';
import { Language } from './Language/Save';

export type ILanguageSuffix = 'FA' | 'EN' | 'AR' | 'SP' | 'FR';

export class Languages {
  public forceUpdate = () => { };
  selectThisLanguage(language: Language): void {
    this.current = language;
    this.languageSuffix =
      this.current.name === 'Persian'
        ? 'FA'
        : this.current.name === 'Arabic'
          ? 'AR'
          : this.current.name === 'France'
            ? 'FR'
            : this.current.name === 'Spanish'
              ? 'SP'
              : 'EN';
    localStorage.setItem('language', this.languageSuffix);
  }

  public languageSuffix: ILanguageSuffix = 'FA';

  public Items: Language[] = [];
  private current?: Language;

  public get isRightToLeft() {
    return this.current?.isRightToLeft || false;
  }

  public get Current() {
    return this.current!;
  }

  constructor(private mainStateManager: MainStateManager) { }

  private getAllLanguages?: GetAllFactory;
  onChangeLanguage = (callBack: () => void) =>
    this.getAllLanguages!.on('change', callBack);

  loadItems = () => {
    this.forceUpdate();

    this.getAllLanguages = GetAllFactory.buildNew(this.mainStateManager);

    this.getAllLanguages.on('form.wasErrored', () => {
      this.forceUpdate();
    });
    this.getAllLanguages.on('form.wasLoaded', () => {
      // this.mainStateManager.isAmisa = this.getAllLanguages!.get('isAmisa');
      this.Items = this.getAllLanguages!.get('languages');
      this.current = this.Items[0];
      this.forceUpdate();
    });

    // this.getAllLanguages.startToLoad();
  };
}
