import { Language } from './../model/common-model';
import { Container } from 'aurelia-framework';
import { DataProperty, Entity } from 'breeze-client';
import { DialogService } from 'aurelia-dialog';
import { IncompleteMlField, IncompleteMultilingualField } from './incomplete-multilingual-field/incomplete-multilingual-field';
import { Utils } from './utils';
import { TranslatedPropertyHelper } from './translated-property-helper';
import { Config } from '../config';

export class UtilsMlField {
  public static getLanguageColumnName(language: Language): string {
    return language._columnName;
  }

  public static isFilled(language: Language, incompleteMlField: IncompleteMlField): boolean {
    return !Utils.isNullOrEmpty(incompleteMlField.prop[language._columnName]);
  }

  public static async checkMultilingualField(entity: Entity, mlProps: Array<IncompleteMlField> = [], configuredLanguages?: Array<Language>): Promise<boolean> {
    let dialogService = Container.instance.get(DialogService);
    if (configuredLanguages == null) {
      configuredLanguages = Container.instance.get(Config).globalConfig.configuredLanguages;
    }

    if (mlProps?.length == 0) {
      // Get each TranslatedProperty of first level on Entity
      let entityName = entity.entityType.shortName.toLocaleLowerCase();
      for (const prop of (entity.entityType.getProperties() as DataProperty[])) {
        let propType = (prop.dataType as any)?.shortName ?? prop.dataType?.getName();
        if (propType == "TranslatedProperty") {
          let propName = prop.name;
          mlProps.push({ prop: entity[propName], label: entityName + "." + propName, isRequired: true, isTextarea: false });
        }
      }
    }
    mlProps.forEach(ml => {
      ml.prop = (TranslatedPropertyHelper.createMissingProperty(ml.prop) as any);
    })
    mlProps = mlProps.filter(x => this.hasToBeFilled(configuredLanguages, x));
    if (mlProps?.length > 0) {
      // Show the dialog to fill in the empty Translations
      return dialogService.open({
        viewModel: IncompleteMultilingualField,
        model: {
          mlProps: mlProps,
          languages: configuredLanguages
        }
      }).whenClosed(result => { return result.output; });
    }
    return true;
  }

  private static hasToBeFilled(configuredLanguages, mlProp: IncompleteMlField): boolean {
    return configuredLanguages.some(l => !this.isFilled(l, mlProp))
      && (mlProp.isRequired || configuredLanguages.some(l => this.isFilled(l, mlProp)));
  }
}
