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 DocumentAccessor, { Document } from '../accessor/document';
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 { BackItem, CommonMenuList, ContentInfo, Headline, NavItem, NavList } from '../component/mod';

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

type DocumentState = {
    doc: Document | 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 DocumentAbout = (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<DocumentState>({ doc: undefined, notfound:false });
    const menu_list = (link?:string) => <CommonMenuList url={link}></CommonMenuList>;
    
    useEffect(() => {
        (async () => {
            if (!isNaN(id)) {
                const c = await DocumentAccessor.findById(id);
                setInfo({ doc: c, notfound: c === undefined });
            }
        })();
    }, []);
    const classes = useStyles();
    console.log(info.doc);
    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.doc === undefined) {
        return (<Headline menu={menu_list()}>
            <LoadingCircle />
        </Headline>
        );
    }
    else{
        const ReaderPage = getPresenter(info.doc);
        return (<Switch>
        <Route exact path={`${prop.match.path}/:id`}>
            <Headline menu={menu_list()}>
                <ContentInfo document={info.doc}></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 doc={info.doc}></ReaderPage>
            </Headline>
        </Route>
        <Route>
            <Headline menu={menu_list()}>
                <div>404 Not Found invalid url : {prop.match.path}</div>
            </Headline>
        </Route>
    </Switch>);
    }
}