import React, { useState, useEffect } from "react";
import { Flex, Image as UIImage, IconButton, Box } from "theme-ui";
import db from "../../database";
import RemoveMapIcon from "../../icons/RemoveMapIcon";
import ResetMapIcon from "../../icons/ResetMapIcon";
import ExpandMoreDotIcon from "../../icons/ExpandMoreDotIcon";
function MapTile({
map,
isSelected,
onMapSelect,
onMapRemove,
onMapReset,
onSubmit,
}) {
const [isMapTileMenuOpen, setIsTileMenuOpen] = useState(false);
const [hasMapState, setHasMapState] = useState(false);
useEffect(() => {
async function checkForMapState() {
const state = await db.table("states").get(map.id);
if (
state &&
(Object.values(state.tokens).length > 0 || state.drawActions.length > 0)
) {
setHasMapState(true);
}
}
checkForMapState();
}, [map]);
const expandButton = (
{
e.preventDefault();
e.stopPropagation();
setIsTileMenuOpen(true);
}}
bg="overlay"
sx={{ borderRadius: "50%" }}
m={1}
>
);
function removeButton(map) {
return (
{
e.preventDefault();
e.stopPropagation();
setIsTileMenuOpen(false);
onMapRemove(map.id);
}}
bg="overlay"
sx={{ borderRadius: "50%" }}
m={1}
>
);
}
function resetButton(map) {
return (
{
e.preventDefault();
e.stopPropagation();
setHasMapState(false);
setIsTileMenuOpen(false);
onMapReset(map.id);
}}
bg="overlay"
sx={{ borderRadius: "50%" }}
m={1}
>
);
}
return (
{
setIsTileMenuOpen(false);
onMapSelect(map);
}}
onDoubleClick={(e) => {
if (!isMapTileMenuOpen) {
onMapSelect(map);
onSubmit(e);
}
}}
>
{/* Show expand button only if both reset and remove is available */}
{isSelected && (
{map.default && hasMapState && resetButton(map)}
{!map.default && hasMapState && !isMapTileMenuOpen && expandButton}
{!map.default && !hasMapState && removeButton(map)}
)}
{/* Tile menu for two actions */}
{!map.default && isMapTileMenuOpen && isSelected && (
setIsTileMenuOpen(false)}
>
{!map.default && removeButton(map)}
{hasMapState && resetButton(map)}
)}
);
}
export default MapTile;