import * as React from 'react'
import CloseButton from '@msgba/components/close-button'
import { sendSaveRequest } from '@msgba/packet'

export interface OverlayMenuProps {
    hiddenMenu: boolean
    setHiddenMenu: (c: boolean) => void
    emulationStarted: boolean
    setHiddenFormSelectFiles: (c: boolean) => void
    screenRef: React.RefObject<HTMLDivElement>
    isFullscreen: boolean
    setIsFullscreen: (c: boolean) => void
    firstMenuElement: React.RefObject<HTMLAnchorElement>
    websocket: WebSocket | null
    onSaveResponseLambdas: Map<bigint, (saveFile: Uint8Array) => void>
};

type Style = Record<string, string>

export default function OverlayMenu ({
    hiddenMenu, setHiddenMenu, emulationStarted,
    setHiddenFormSelectFiles, screenRef, isFullscreen, setIsFullscreen,
    firstMenuElement, websocket, onSaveResponseLambdas
}: OverlayMenuProps): JSX.Element {
    function exitMenu (): void {
        setHiddenMenu(true)
    }

    function openSelectFilesMenu (): void {
        setHiddenFormSelectFiles(false)
    }

    function toggleFullscreen (): void {
        if (isFullscreen) {
            document.exitFullscreen().catch((c: string) => { console.log(c) })
            setIsFullscreen(false)
        }

        if (screenRef.current != null) {
            screenRef.current.requestFullscreen().then(() => {
                setIsFullscreen(true)
            }).catch((error: string) => {
                console.log(error)
            })
        }
    }

    const styleSelectRom: Style = {}
    if (emulationStarted) {
        styleSelectRom.display = 'none'
    }

    const styleMenu: Style = {}
    if (hiddenMenu) {
        styleMenu.display = 'none'
    }
    let toggleFullscreenText: string = 'Set fullscreen'
    if (isFullscreen) {
        toggleFullscreenText = 'End fullscreen'
    }

    const saveButton = React.useRef<HTMLAnchorElement>(null)
    const [saveIdentifier, setSaveidentifier] = React.useState<bigint>(0n)

    function onSave (): void {
        if (websocket == null) {
            console.log('No websocket still')
            return
        }
        const currentSave = saveIdentifier
        setSaveidentifier((c: bigint) => c + 1n)
        console.log('Reachs here')
        onSaveResponseLambdas.set(currentSave, (saveFile: Uint8Array) => {
            const anchor = document.createElement('a')
            const blobSaveResponseFile = new Blob([saveFile.buffer])
            const fileReader = new FileReader()
            fileReader.onload = () => {
                if (typeof fileReader.result === 'string') {
                    anchor.style.display = 'none'
                    document.body.appendChild(anchor)
                    anchor.href = fileReader.result
                    anchor.download = 'ruby.ss1'
                    anchor.click()
                    return true
                }
                return false
            }
            fileReader.readAsDataURL(blobSaveResponseFile)
        })
        console.log(onSaveResponseLambdas)
        sendSaveRequest(websocket, currentSave)
    }

    const styleSave: Style = {}
    if (!emulationStarted) {
        styleSave.display = 'none'
    }

    return (
        <div style={styleMenu} className="overlay-menu-div">
            <div className="overlay-menu-div-header">
                <CloseButton onClick={exitMenu}/>
            </div>
            <div className="overlay-menu">
                <ul>
                    <li><a ref={firstMenuElement} style={styleSelectRom} onClick={openSelectFilesMenu} href="#">Select rom</a></li>
                    <li><a ref={saveButton} style={styleSave} onClick={onSave} href="#">Save</a></li>
                    <li><a onClick={toggleFullscreen} href="#">{toggleFullscreenText}</a></li>
                    <li><a href="#" onClick={exitMenu}>Exit</a></li>
                </ul>
            </div>
        </div>
    )
}
