<script>
	import TopAppBar, { Row, Section, Title as PageTitle } from '@smui/top-app-bar';  import IconButton from '@smui/icon-button';
	import Drawer, { AppContent, Content, Header, Scrim, Title, Subtitle } from '@smui/drawer';
	import Snackbar, { Actions, Label as SnackLabel } from '@smui/snackbar';
	import Button, { Label } from '@smui/button';
	import List, { Item, Text, Graphic } from '@smui/list';
	import { BleClient } from '@capacitor-community/bluetooth-le';
	import { Geolocation } from '@capacitor/geolocation';
	import { page } from '$app/stores';

	import { gpsLat, gpsLon, temperature, humidity, pressure, bsec, co2, gas, quaternion } from '$lib/dataStore';


	let gpsLatData = 0;
	$: gpsLat.set(gpsLatData);

	let gpsLonData = 0;
	$: gpsLon.set(gpsLonData);

	let temperatureData = 0;
	$: temperature.set(temperatureData);

	let humidityData = 0;
	$: humidity.set(humidityData);

	let pressureData = 0;
	$: pressure.set(pressureData);

	let bsecData = 0;
	$: bsec.set(bsecData);

	let co2Data = 0;
	$: co2.set(co2Data);

	let gasData = 0;
	$: gas.set(gasData);

	let quaternionData = {
		x: 0,
		y: 0,
		z: 0
	};
	$: quaternion.set(quaternionData);

	// export async function getCurrentPosition() {
	// 	const res = await Geolocation.getCurrentPosition();
	// 	gpsLatData = res?.coords.latitude;
	// 	gpsLonData = res?.coords.longitude;
	// }

  
	let open = false;
	let active = 'Dashboard';
  
	function setActive(value) {
		active = value;
		open = false;
	}
  
	function getStr(input) {
		return `19b10000-${input}-537e-4f6c-d104768a1214`;
	}
	const NICLA_SERVICE = getStr("0000");
	const TEMPERATURE_CHARACTERISTIC = getStr("2001"); // float
	const HUMIDITY_CHARACTERISTIC = getStr("3001"); // uint8
	const PRESSURE_CHARACTERISTIC = getStr("4001"); // float

	const ACCELEROMETER_CHARACTERISTIC = getStr("5001"); // array 3x 2 bytes, XY
	const GYROSCOPE_CHARACTERISTIC = getStr("6001"); // array 3x 2 bytes, XYZ
	const QUATERNION_CHARACTERISTIC = getStr("7001"); // array 4x 2 bytes, XYZW

	const LED_CHARACTERISTIC = getStr("8001"); // array 3 bytes
	const BSEC_CHARACTERISTIC = getStr("9001");
	const CO2_CHARACTERISTIC = getStr("9002"); // uint32
	const GAS_CHARACTERISTIC = getStr("9003");
	const GPS_CHARACTERISTIC = getStr("9004"); // array 3x 2 bytes


	export async function readTemperature() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				TEMPERATURE_CHARACTERISTIC
			);
			temperatureData = result.getFloat32(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}

	export async function readHumidty() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				HUMIDITY_CHARACTERISTIC
			);
			humidityData = result.getUint8(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}

	export async function readPressure() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				PRESSURE_CHARACTERISTIC
			);
			pressureData = result.getFloat32(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}

	export async function readBSEC() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				BSEC_CHARACTERISTIC
			);
			bsecData = result.getFloat32(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}
	
	export async function readCO2() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				CO2_CHARACTERISTIC
			);
			co2Data = result.getUint32(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}

	export async function readGas() {
		try {
			const result = await BleClient.read(
				device.deviceId,
				NICLA_SERVICE,
				GAS_CHARACTERISTIC
			);
			gasData = result.getUint32(0, true).toFixed(2);
		} catch (error) {
			console.error(error);
		}
	}

	let device;
	let connected = false;
	let intervalId;
	let snackbarWithoutClose;
	export async function main() {
		try {
			await BleClient.initialize({ androidNeverForLocation: true });

			device = await BleClient.requestDevice({
				services: [NICLA_SERVICE]
			});

			await BleClient.connect(device.deviceId, () => { connected = false});
			connected = true;
			snackbarWithoutClose.open();

			await BleClient.startNotifications(
				device.deviceId,
				NICLA_SERVICE,
				QUATERNION_CHARACTERISTIC,
				(value) => {
					$: quaternionData.x = value.getFloat32(0, true).toFixed(2);
					$: quaternionData.y = value.getFloat32(4, true).toFixed(2);
					$: quaternionData.z = value.getFloat32(8, true).toFixed(2);
				}
			);


			// getCurrentPosition();
			readTemperature();
			readHumidty();
			readPressure();
			readCO2();
			readBSEC();
			readGas();
			intervalId = setInterval(function() {
				// getCurrentPosition();
				readTemperature();
				readHumidty();
				readPressure();
				readCO2();
				readBSEC();
				readGas();
			}, 5000);

		} catch (error) {
			console.error(error);
		}
	}

	export async function disconnect() {
		try {
			clearInterval(intervalId);
			await BleClient.disconnect( device.deviceId );
		} catch (error) {
			console.error(error);
		}
	}

	// import { Preferences } from '@capacitor/preferences';

	// async function setObject() {
	// 	await Preferences.set({
	// 		key: 'user',
	// 		value: JSON.stringify({
	// 		id: 1,
	// 		name: 'Max'
	// 		})
	// 	});
	// }

	// async function getObject() {
	// 	const ret = await Preferences.get({ key: 'user' });
	// 	const user = JSON.parse(ret.value);
	// }
</script>


<div class="drawer-container">
	<Drawer variant="modal" bind:open>
		<Header>
			<Title>WeatherWand</Title>
		</Header>
		<Content>
			<List>
				<Item href="/"	on:click={() => setActive('Dashboard')}	activated={active === 'Dashboard'}>
					<Graphic class="material-icons" aria-hidden="true">dashboard</Graphic>
					<Text>Dashboard</Text>
				</Item>
				<Item href="/daten"	on:click={() => setActive('Rohdaten')}	activated={active === 'Rohdaten'}>
					<Graphic class="material-icons" aria-hidden="true">storage</Graphic>
					<Text>Rohdaten</Text>
				</Item>
				<Item href="ble" on:click={() => setActive('BLE-Verbindung')} activated={active === 'BLE-Verbindung'}>
					<Graphic class="material-icons" aria-hidden="true">bluetooth</Graphic>
					<Text>BLE-Verbindung</Text>
				</Item>
				<!-- <Item href="einstellungen" on:click={() => setActive('Einstellungen')} activated={active === 'Einstellungen'}>
					<Graphic class="material-icons" aria-hidden="true">settings</Graphic>
					<Text>Einstellungen</Text>
				</Item> -->
			</List>
		</Content>
	</Drawer>
	<Scrim />
	<AppContent class="app-content">
		<div class="top-app-bar-container flexor">
			<TopAppBar variant="static" color='primary'>
				<Row>
					<Section>
						<IconButton class="material-icons" on:click={() => (open = !open)}>menu</IconButton>
						<PageTitle>{active}</PageTitle>
					</Section>
					<Section align="end" toolbar>
						<IconButton on:click={() => setActive('BLE-Verbindung')} href="ble" class="material-icons" aria-label="Go to bluetooth settings">bluetooth</IconButton>
					</Section>
				</Row>
			</TopAppBar>
			<div class="flexor-content">
				<main class="main-content">
					<!-- <pre class="status">Active: {active}</pre> -->
					<slot />

					{#if $page.url.pathname.slice($page.url.pathname.lastIndexOf('/')) == "/ble"}
						<br>
						<br>
						{#if connected}
							<Button on:click={disconnect} color="secondary" variant="unelevated">
								<Label>Nicla trennen</Label>
							</Button>
						{:else}
							<Button on:click={main} variant="unelevated">
								<Label>Nicla verbinden</Label>
							</Button>
						{/if}
					{/if}
				</main>
			</div>
		</div>
	</AppContent>
	<Snackbar bind:this={snackbarWithoutClose}>
		<SnackLabel>Nicla erfolgreich verbunden.</SnackLabel>
		<Actions>
			<Button on:click={() => setActive('Dashboard')} href="/" color="secondary" variant="unelevated">
				<Label>Dashboard</Label>
			</Button>
		</Actions>
	</Snackbar>
</div>

<style>
	:global(body) {
		margin: 0;
		font-family: Roboto;
	}

	.flexor-content {
		padding: 1rem;
	}
</style>