"use strict";

const React = require("react");
const classnames = require("classnames");

const Layout = require("../layout");
const gql = require("../../../graphql/tag");

function PartitionEntry({partition, isLast}) {
	return (
		<tr className={classnames("partition", {last: isLast})}>
			<td>{partition.name}</td>
			<td>{partition.size.toString()}</td>
			<td colSpan={5}>
				{(partition.mountpoint != null)
					? partition.mountpoint
					: <span className="notMounted">(not mounted)</span>
				}
			</td>
		</tr>
	);
}

function DriveEntry({drive}) {
	let hasPartitions = (drive.partitions.length > 0);

	return (<>
		<tr className={classnames({hasPartitions})}>
			<td className={classnames("smart", drive.smartHealth)} rowSpan={1 + drive.partitions.length} />
			<td>{drive.blockDevice.name}</td>
			<td>{drive.size.toDisplay(2).toString()}</td>
			<td>{drive.rpm} RPM</td>
			<td>{drive.serialNumber}</td>
			<td>{drive.model}</td>
			<td>{drive.modelFamily}</td>
			<td>{drive.firmwareVersion}</td>
		</tr>
		{drive.partitions.map((partition, i) => {
			let isLast = (i === drive.partitions.length - 1);

			return <PartitionEntry partition={partition} isLast={isLast} />;
		})}
	</>);
}

module.exports = {
	query: gql`
		query {
			hardware {
				drives {
					smartHealth
					size
					rpm
					serialNumber
					model
					modelFamily
					firmwareVersion

					blockDevice {
						name
					}

					partitions: allBlockDevices(type: PARTITION) {
						name
						mountpoint
						size
					}
				}
			}
		}
	`,
	template: function StorageDeviceList({data}) {
		return (
			<Layout title="Storage Devices">
				<table className="drives">
					<tr>
						<th>SMART</th>
						<th>Device</th>
						<th>Total size</th>
						<th>RPM</th>
						<th>Serial number</th>
						<th>Model</th>
						<th>Family</th>
						<th>Firmware version</th>
					</tr>
					{data.hardware.drives.map((drive) => <DriveEntry drive={drive} />)}
				</table>
			</Layout>
		);
	}
};