import React, { useContext, useEffect, useState } from 'react';
import { CommonMenuList, Headline } from "../component/mod";
import { UserContext } from "../state";
import { Box, Grid, Paper, Typography,Button, makeStyles, Theme } from "@material-ui/core";

const useStyles = makeStyles((theme:Theme)=>({
    paper:{
        padding: theme.spacing(2),
    },
    commitable:{
        display:'grid',
        gridTemplateColumns: `100px auto`,
    },
    contentTitle:{
        marginLeft: theme.spacing(2)
    }
}));

export function DifferencePage(){
    const ctx = useContext(UserContext);
    const classes = useStyles();
    const [diffList,setDiffList] = useState<
        {type:string,value:{path:string,type:string}[]}[]
    >([]);
    const doLoad = async ()=>{
        const list = await fetch('/api/diff/list');
        if(list.ok){
           const inner = await list.json();
           setDiffList(inner);
        }
        else{
            //setDiffList([]);
        }
    };
    useEffect(
        ()=>{
            doLoad();
            const i = setInterval(doLoad,5000);
            return ()=>{
                clearInterval(i);
            }
        },[]
    )
    const Commit = async(x:{type:string,path:string})=>{
        const res = await fetch('/api/diff/commit',{
            method:'POST',
            body: JSON.stringify([{...x}]),
            headers:{
                'content-type':'application/json'
            }
        });
        const bb = await res.json();
        if(bb.ok){
            doLoad();
        }
    } 
    const menu = CommonMenuList();
    (ctx.username == "admin")
    return (<Headline menu={menu}>
        {(ctx.username == "admin") ? (diffList.map(x=><Paper key={x.type} className={classes.paper}>
            <Typography variant='h3' className={classes.contentTitle}>{x.type}</Typography>
            <Box className={classes.commitable}>
                {x.value.map(y=>(
                    <>
                    <Button key={`button_${y.path}`} onClick={()=>Commit(y)}>Commit</Button>
                    <Typography key={`typography_${y.path}`} variant='h5'>{y.path}</Typography>
                    </>))}
            </Box>
        </Paper>)):(<Typography variant='h2'>Not Allowed : please login as an admin</Typography>)
        }
    
    </Headline>)
}