import React, {createContext} from 'react'
import OnePageView from './OnePageView'

export const BookContext = createContext({})

export interface IBookPage {
    src: string
    alt?: string
    thumbnail?: string
}

export const bookViewModes = [
    {
        text: 'One Page',
        value: 'one page',
        icon: ''
    },
    {
        text: 'Two Pages',
        value: 'two pages',
        icon: ''
    }
]

export enum BookViewMode {
    onePage = 'one page',
    twoPages = 'two pages'
}

export interface IBookContext {
    currIndex?: number,
    src?: IBookPage[],
    flagToReverse?: boolean,
    mode?: BookViewMode,
    readonly setBookContextState: (newState: any)=> undefined
}


class BookComponent extends React.Component<any>{
    constructor(props: any){
        super(props)
        this.state = {
            currIndex: 0,
            src: [],
            flagToReverse: false,
            mode: "one page",
            setBookContextState: (newState: IBookContext)=>{
                this.setState(oldState=> ({
                    ...oldState,
                    ...newState
                }))
            }
        } 
    }

    componentDidMount(){
        fetch('https://picsum.photos/v2/list')
            .then(response=>{
                return response.json()
            }).then(data=>{
                data = data.map((item: any)=>{
                    return {
                        src: item.download_url,
                        alt: item.author
                    }
                })

                this.setState({
                    src: data
                })
            })
    }
    
    render(){
        return <BookContext.Provider value={{...this.state}}>
            <BookContext.Consumer>
                {state=>(
                    <>
                        <OnePageView {...state}/>
                    </>
                )}
            </BookContext.Consumer>
        </BookContext.Provider>
    }
}

export default BookComponent