import React, { useState, useEffect, useContext } from 'react';
import { Redirect, Route, Switch, useHistory, useRouteMatch, match as MatchType, Link as RouterLink, useParams, useLocation } from 'react-router-dom';
import ContentAccessor, { Content } from '../accessor/contents';
import { LoadingCircle } from '../component/loading';
import { Link, Paper, makeStyles, Theme, Box, useTheme, Typography } from '@material-ui/core';
import {ArrowBack as ArrowBackIcon } from '@material-ui/icons';
import { getPresenter } from './reader/reader';
import { ContentInfo, Headline, NavItem, NavList } from '../component/mod';
import {BackLinkContext} from '../state';

export const makeContentInfoUrl = (id: number) => `/doc/${id}`;
export const makeMangaReaderUrl = (id: number) => `/doc/${id}/reader`;

type ContentState = {
    content: Content | undefined,
    notfound: boolean,
}

const useStyles = makeStyles((theme:Theme)=>({
    noPaddingContent:{
        display:'flex',
        flexDirection: 'column',
        flexGrow: 1,
    },
    noPaddingToolbar:{
        flex: '0 1 auto',
        ...theme.mixins.toolbar,
    }
}));

export const ContentAbout = (prop: { match: MatchType }) => {
    const match = useRouteMatch<{id:string}>("/doc/:id");
    if (match == null) {
        throw new Error("unreachable");
    }
    const id = Number.parseInt(match.params['id']);
    const [info, setInfo] = useState<ContentState>({ content: undefined, notfound:false });
    const location = useLocation();
    console.log("state : "+location.state);
    const menu_list = (link?:string)=>(
        <NavList>
            <BackLinkContext.Consumer>
            {
                (ctx) => link === undefined ?
                <NavItem name="Back" to={ctx.path} icon={<ArrowBackIcon/>}/>
                : <NavItem name="Back" to={link} icon={<ArrowBackIcon/>}/>
            }
            </BackLinkContext.Consumer>
        </NavList>
    );
    
    useEffect(() => {
        (async () => {
            console.log("mount content about");
            if (!isNaN(id)) {
                const c = await ContentAccessor.findById(id);
                setInfo({ content: c, notfound: c === undefined });
            }
        })()
        return ()=>{console.log("unmount content about")}
    }, []);
    const classes = useStyles();
    
    if (isNaN(id)) {
        return (
            <Headline menu={menu_list()}>
                <Typography variant='h2'>Oops. Invalid ID</Typography>
            </Headline>
        );
    }
    else if(info.notfound){
        return (
            <Headline menu={menu_list()}>
                <Typography variant='h2'>Content has been removed.</Typography>
            </Headline>
        )
    }
    else if (info.content === undefined) {
        return (<Headline menu={menu_list()}>
            <LoadingCircle />
        </Headline>
        );
    }
    else{
        const ReaderPage = getPresenter(info.content);
        return (<Switch>
        <Route exact path={`${prop.match.path}/:id`}>
            <Headline menu={menu_list()}>
                <ContentInfo content={info.content}></ContentInfo>
            </Headline>
        </Route>
        <Route exact path={`${prop.match.path}/:id/reader`}>
            <Headline menu={menu_list(`${prop.match.path}/${id}`)} classes={{
                content:classes.noPaddingContent,
                toolbar:classes.noPaddingToolbar
                }}>
                <ReaderPage content={info.content}></ReaderPage>
            </Headline>
        </Route>
        <Route>
            <Headline menu={menu_list()}>
                <div>404 Not Found invalid url : {prop.match.path}</div>
            </Headline>
        </Route>
    </Switch>);
    }
}