import { SAMPA } from "../sampa";

class Phoneme<
  C extends string,
	SC extends string,
  V extends string,
	SV extends string,
> {
  private _phoneme: string | null;
  private _letters: string;

  constructor(phoneme: string | null, letters: string) {
    this._phoneme = phoneme;
    this._letters = letters;
  }

  get letters(): string {
    return this._letters;
  }

	set letters(value: string){
		this._letters = value;
	}

  get phoneme(): string | null {
    return this._phoneme;
  }

	set phoneme(value: string){
		this._phoneme = value;
	}

  isPhoneme(): boolean {
    return this._phoneme !== null;
  }

  isConsonant(consonants: Record<C, string>): boolean {
    return this._phoneme !== null && this._phoneme in consonants;
  }

  isVowel(vowels: Record<V, string>): boolean {
    return this._phoneme !== null && this._phoneme in vowels;
  }

  isSemiConsonant(semiConsonants: Record<SC, string>): boolean {
    return this._phoneme !== null && this._phoneme in semiConsonants;
  }

  isMutedPhoneme(): boolean {
    return this._phoneme === SAMPA.specials["#"];
  }

  isSemiVowel(semiVowels: Record<SV, string>): boolean {
    return this._phoneme !== null && this._phoneme in semiVowels;
  }

  isConsonantDouble(consonants: Record<C, string>, semiConsonants: Record<SC, string>): boolean {
    return (
      this.isPhoneme() &&
      (this.isConsonant(consonants) || this.isSemiConsonant(semiConsonants)) &&
      this._letters.length === 2 &&
      this._letters[0] === this._letters[1]
    );
  }

  simplifyDouble(consonants: Record<C, string>, semiConsonants: Record<SC, string>): void {
    if (this.isConsonantDouble(consonants, semiConsonants)) {
      this._letters = this._letters[0];
    }
  }
}

class Syllabe<
  C extends string,
	SC extends string,
  V extends string,
	SV extends string,
> {
  private _phonemes: Phoneme<C, SC, V, SV>[];

  constructor() {
    this._phonemes = [];
  }

  get phonemes(): Phoneme<C, SC, V, SV>[] {
    return this._phonemes;
  }

  addPhonemes(indicesOrObjects: (number | Phoneme<C, SC, V, SV>)[], phonemes?: Phoneme<C, SC, V, SV>[]): void {
    if (!phonemes) {
      this._phonemes.push(...(indicesOrObjects as Phoneme<C, SC, V, SV>[]));
    } else {
      for (const i of indicesOrObjects as number[]) {
        this._phonemes.push(phonemes[i]);
      }
    }
  }

  toHTML(container: HTMLElement): HTMLElement {
    for (const element of this._phonemes) {
      const span = document.createElement("span");
      if (element.isMutedPhoneme()){
				span.classList.add("muted");
			}
      span.textContent = element.letters;
      container.appendChild(span);
    }
    return container;
  }
}

export { Phoneme, Syllabe };