import { createContext, useEffect, useReducer } from "react"
import {useLocation} from 'react-router-dom'
import { fromEvent } from "rxjs"

const data ={
    device:'',
    currentPage:'',
    pageIndex:0,
    theme:'light'
}
export const AppContext = createContext<{data:typeof data,dispatch:any}>({
    data:data,
    dispatch:()=>null
})

interface Actions {
    type: string
    payload: any
}
const AppReducer = (state:typeof data,action:Actions)=>{
    const {type,payload} = action
     switch(type){
        case 'slideOnChange':
            state.pageIndex = payload.pageIndex
            if(state.currentPage==='/chain33'&&state.pageIndex===1){
                state.theme = 'dark'
            }else{
                state.theme = 'light'
            }    
        break;
        case 'routerOnChange':
            state.currentPage = payload.currentPage
        break;
    }
    return {...state}
}

export const AppProvider = (props: any)=>{
    const [state,dispatch] = useReducer(AppReducer,data)
    const location = useLocation()
    const ob = fromEvent(window,'resize')
    useEffect(()=>{
        dispatch({type:'routerOnChange',payload:{currentPage:location.pathname}})
        dispatch({type:'slideOnChange',payload:{pageIndex:0}})
    },[location])
    useEffect(()=>{
  
    //    ob.subscribe(v=>{
    //         const target = v.currentTarget
    //         if(target){
    //             console.log(target);
                
    //         }
    //    })
    })
    return(
        <AppContext.Provider value={{data:state,dispatch}}>
            {props.children}
        </AppContext.Provider>
    )
}