import { Component } from 'solid-js';
import { IVisibilityActionRequest, MatrixCapabilities, WidgetApi, WidgetApiToWidgetAction } from 'matrix-widget-api';
import { HopeProvider } from "@hope-ui/solid";

import { BusinessDataProvider } from './businessData';
import { SearchProvider } from './search';
import { PassagesDisplay } from './passagesDisplay';
import { StopsManager } from './stopsManager';

import styles from './App.module.css';


function parseFragment() {
	const fragmentString = (window.location.hash || "?");
	return new URLSearchParams(fragmentString.substring(Math.max(fragmentString.indexOf('?'), 0)));
}

const App: Component = () => {

	console.log('App: New');

	const qs = parseFragment();
	const widgetId = qs.get('widgetId');
	const userId = qs.get('userId');

	console.log("App: widgetId:" + widgetId);
	console.log("App: userId:" + userId);

	const api = new WidgetApi(widgetId != null ? widgetId : undefined);
	api.requestCapability(MatrixCapabilities.AlwaysOnScreen);
	api.start();
	api.on("ready", function() {
		console.log("App: widget API is READY !!!!");
	});

	// Seems to don´t be used...
	api.on(`action:${WidgetApiToWidgetAction.UpdateVisibility}`, (ev: CustomEvent<IVisibilityActionRequest>) => {
		console.log("App: Visibility change");
		ev.preventDefault(); // we're handling it, so stop the widget API from doing something.
		console.log("App: ", ev.detail); // custom handling here
		/* api.transport.reply(ev.detail, <IWidgetApiRequestEmptyData>{}); */
		api.transport.reply(ev.detail, {});
	});

	return (
		<BusinessDataProvider>
			<SearchProvider>
				<HopeProvider>
					<div class={styles.App} data-panelsnap-id="1">
						<div class={styles.panel}>
							<StopsManager />
						</div>
						<div class={styles.panel}>
							<PassagesDisplay />
						</div>
					</div>
				</HopeProvider>
			</SearchProvider>
		</BusinessDataProvider>
	);
};

export default App;
