import { useEffect, useState } from "react";
import { BimViewer } from "@pattern-x/gemini-viewer";
import { ViewpointTable } from "../indexeddb/ViewpointTable";
import "../css/Viewpoints.scss";
import { ReactComponent as CloseSvg } from "../assets/svg/close.svg";
import { ReactComponent as PlusSvg } from "../assets/svg/plus.svg";
import { ReactComponent as DeleteSvg } from "../assets/svg/delete.svg";
import { ReactComponent as DCaretSvg } from "../assets/svg/d-caret.svg";
import { useAppSelector, useAppDispatch } from '../store/Hooks';

import { setVisibility } from '../store/ViewpointsSlice';

interface ViewpointsProps {
    projectId: string;
    bimViewer?: BimViewer;
}

export const Viewpoints = ({ projectId, bimViewer }: ViewpointsProps) => {
    const [viewpoints, setViewpoints] = useState([]);
    const visible = useAppSelector(state => state.viewpoints.value);
    const dispatch = useAppDispatch();

    useEffect(() => {
        if (!projectId) {
            console.warn(`[Viewpoint] No projectId specified!`);
            return;
        }
        ViewpointTable.instance().query(projectId, (viewpoints: any[]) => { // eslint-disable-line
            setViewpoints(viewpoints as never[]);
        }, (err: any) => {
            console.log(`[Viewpoint] error: ${err}`)
        });
    }, [projectId])

    const handleViewpointClick = ($event: any, vp: any) => {
        $event.stopPropagation();
        if (!bimViewer || !bimViewer.bcfViewpointsPlugin || !vp) {
            return;
        }
        const bcfPlugin = bimViewer.bcfViewpointsPlugin;
        bcfPlugin.setViewpoint(vp);
    }

    const deleteViewpoint = ($event: any, vp: any) => {
        $event.stopPropagation();
        const index = viewpoints.findIndex((item: any) => item.id === vp.id); // eslint-disable-line
        if (index !== -1) {
            console.log(`[Viewpoint] Deleting ${vp.id}`);
            ViewpointTable.instance().delete(vp.id);
            viewpoints.splice(index, 1);
            setViewpoints(viewpoints.filter((item: any) => item.id !== vp.id) as never[]);
        }
    }

    const addViewpoint = ($event: any) => {
        $event.stopPropagation();
        if (!bimViewer || !bimViewer.bcfViewpointsPlugin) {
            return;
        }
        const bcfPlugin = bimViewer.bcfViewpointsPlugin;
        const viewpoint = bcfPlugin.getViewpoint({
            spacesVisible: false, // Default
            spaceBoundariesVisible: false, // Default
            openingsVisible: false, // Default
            snapshot: true,
        });

        viewpoint.projectId = projectId;
        ViewpointTable.instance().add(viewpoint, (event: any) => { // eslint-disable-line
            const id = event.target.result;
            viewpoint.id = id; // now 'id' is generated by indexedDb, store it
            viewpoints.push(viewpoint as never);
            setViewpoints(viewpoints.filter((item: any) => item.id !== undefined) as never[]);
        }, (err: any) => {
            console.log(`[Viewpoint] error:${err}`)
        });
    }

    return (
        <div className="panel" style={{ display: visible ? "flex" : "none" }}>
            <div className="header">
                <span className="title">视点</span>
                <i className="icon close" onClick={() => dispatch(setVisibility(false))}>
                    <CloseSvg />
                </i>
            </div>
            <div className="body">
                <div className="operations">
                    <button className="operation-icon" onClick={addViewpoint}>
                        <PlusSvg />
                    </button>
                </div>
                <div className="viewpoints">
                    {
                        viewpoints.map((vp: any) => {
                            return (
                                <div className="viewpoint" onClick={($event) => handleViewpointClick($event, vp)} key={vp.id} title={vp.id}>
                                    <img src={vp.snapshot.snapshot_data} className="snapshot" alt="" />
                                    <i className="icon delete" onClick={($event) => deleteViewpoint($event, vp)} title="删除视点">
                                        <DeleteSvg />
                                    </i>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className="footer">
                <div className="resize">
                    <i className="icon">
                        <DCaretSvg></DCaretSvg>
                    </i>
                </div>
            </div>
        </div>
    )
}