import * as React from 'react';

import { makeStyles, Theme } from '@material-ui/core/styles';

import Box from '@material-ui/core/Box';
import Container from '@material-ui/core/Container';

import { Tiling } from './types';
import { useReadFile } from './util';

const useStyles = makeStyles((theme: Theme) => ({
	container: {
		display: 'flex',
		flexWrap: 'wrap',
	},
	tile: {
		imageRendering: 'pixelated',
		border: `solid 1px ${theme.palette.divider}`,
		background: theme.palette.background.paper,
		width: 128,
		height: 128,
		margin: 4,
	},
}));

const tilings: Tiling[] = [
	{
		size: 1,
		sprite: { name: 'dirt' },
	},
	{
		size: 1,
		sprite: { name: 'grass' },
	},
	{
		size: 1,
		sprite: { name: 'road_left' },
	},
	{
		size: 1,
		sprite: { name: 'road_right' },
	},
];

interface TilingDisplayProps {
	tiling: Tiling;
}

function TilingDisplay({ tiling }: TilingDisplayProps): JSX.Element | null {
	const classes = useStyles();

	let name: string;

	switch (tiling.size) {
		case 1:
			name = tiling.sprite.name;
			break;
		case 3:
			name = tiling.sprites[1][1].name;
			break;
	}

	const path = `static/resources/sprite/tile/${name}.png`;
	const image = useReadFile(path, 'base64');

	return <img src={image ? `data:image/png;base64,${image}` : undefined} className={classes.tile} />;
}

export function Library(): JSX.Element {
	const classes = useStyles();

	return (
		<Container>
			<Box display='inline-block'>
				<div className={classes.container}>
					{tilings.map((tiling, i) => (
						<TilingDisplay key={i} tiling={tiling} />
					))}
				</div>
			</Box>
		</Container>
	);
}
