import { syllables } from "./pinyin"
import { BtnColor, SylPart, Syllable } from "./types"

export const isEnabled = (arr: SylPart[], find: string): boolean => arr.some((str) => str.index==find)

export const toggleSylPart = ( arr: SylPart[], part: SylPart ):SylPart[] => {
    if ( arr.some((btn) => btn.index==part.index) )
      return arr.filter((el)=>el.index!==part.index)
    else
      return [ ...arr, part]
}

type TComparer = (index: any) => (el: any) => boolean
const SylPartComparer:TComparer = (index: string) => (el: SylPart) => el.index === index
const SylPartFilter:TComparer = (index: SylPart) => (el: SylPart) => el.index !== index.index

const defToggleComparer:TComparer = (index: any) => (el: any) => el === index
const defToggleFilter:TComparer = (index: any) => (el: any) => el !== index

export const toggleSylPartG = ( arr: SylPart[], part: SylPart ):SylPart[] =>
  toggle<SylPart>(arr, part, SylPartComparer, SylPartFilter)

export const included = <T>( arr: T[], part: T, comparer:TComparer = defToggleComparer) =>
  arr.some( comparer(part) )

const exclude = <T>( arr: T[], part: T,
  filter:TComparer = defToggleFilter) => arr.filter( filter(part) )

const include = <T>( arr: T[], part: T):T[] => [ ...arr, part]

export const toggle = <T>( arr: T[], part: T,
                           comparer:TComparer = defToggleComparer,
                           filter:TComparer = defToggleFilter):T[] =>
  included<T>(arr,part, comparer) ? exclude<T>(arr,part, filter ) :  include<T>(arr, part)

export const genrateRandomNumber = (min: number, max: number):number => {
  min = Math.ceil(min)
  max = Math.floor(max)
  const rnd =  Math.floor(Math.random() * (max - min + 1)) + min
  return rnd
}

export const getRandomArray = <T>(fromArray:T[], count:number):T[] => {
  let _tone:T[] = []
  if (fromArray.length==0) {
    return _tone
  }
  for( let x=0; x<count; x++) {
    const randomN = genrateRandomNumber(0,fromArray.length-1)
    _tone = [..._tone, fromArray[randomN]]
  }
  return _tone
}

export const GetSyllablesByInitAndFin = (initiales:SylPart[], finales: SylPart[]):Syllable[] => {
  const inits = initiales.map( (i) => i.index)
  const fins = finales.map( (i) =>i.index )
  return syllables.filter( syl => inits.includes(syl.initiale) && fins.includes(syl.finale) )
  }

export const Outlined = (color: BtnColor):string => `outline-${color}`

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}