import { Context, createContext, Dispatch, useContext } from "react";
import { Action, ToggleType } from "./reducer"
import { Syllable, SylPart, Tone } from "./types";
import { isEnabled } from "./utils";

export interface IState {
    sylCount: number,
    sylPause: number,
    initiales: SylPart[],
    finales: SylPart[],
    allInitiales: boolean,
    allfinales: boolean,
    foundSyllables: Syllable[],
    foundTones: Tone[],
    randomTones: Tone[],
    allEnabled: (type: ToggleType) => false,
    isEnabled: (type: ToggleType, index: string) => false,
    isFound: () => false
}

export interface IStore {
    state: Partial<IState>
    dispatch: Dispatch<Action>
}

export const defaultState:object = {
    sylCount: 10,
    sylPause: 3,
     allfinales: false,
     allInitiales: false,
     finales: [] as SylPart[],
     initiales: [] as SylPart[],
     foundSyllables: [],
     foundTones: [],
     randomTones: [],
     allEnabled: function(type: ToggleType) {
        if ( type === ToggleType.init ) return (this as IState).allInitiales
        if ( type === ToggleType.fin )  return (this as IState).allfinales
        return false
      },
     isEnabled: function(type: ToggleType, index: string) {
        if ( type === ToggleType.init ) return isEnabled((this as IState).initiales!, index)
        if ( type === ToggleType.fin )  return isEnabled((this as IState).finales!, index)
        return false
      },
      isFound: function():boolean { return (this as IState).foundSyllables!.length > 0 }
    }

export const AppContext:Context<IStore> = createContext<IStore>({ state: defaultState as IState, dispatch: () => null })

export const useStateContext = () => useContext(AppContext);
