import React from 'react';

import LinkManager from 'modularity-front';
import Modularity from 'modularity-front';
import {Button ,Col,Row, Input} from 'react-materialize';
let Module = Modularity.Module;

class ViewModule extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
			routes: this.Routes.value || {},
			keys: (() => {
				let keys = Object.keys(this.Routes.value || {});
				keys.sort((a,b) => b.length - a.length);
				return keys;
			})()
		}

		this.Routes.onUpdate((routes) => {
			let keys = Object.keys(routes);
			keys.sort((a,b) => b.length - a.length);
			this.setState({routes, keys});
		})

		

		let route = this.RoutingSystem.getRoute();
		console.log(route.url);
	}

	onChildAdd(modid) {
		let route = this.RoutingSystem.getRoute();
		let url = window.prompt("View URL ", route.url);
		let routes = this.Routes.value || {};
		routes[url] = routes[url] ? [...routes[url], modid] : [modid];
		this.Routes.update(routes);
	}

	getMatchingMods() {
		let route = this.RoutingSystem.getRoute();
		let url = route.url;
		
		let keys = this.state.keys;
		for (let i = 0;i < keys.length; i++) {
			if (url.startsWith(keys[i])) {
				return this.state.routes[keys[i]];
			}
		}
		// console.log("Routes ", keys);
		return this.state.routes[route.url];
	}

	render() {
		let subview = this.getMatchingMods() || [];
		return <div>
			{subview.map((id) => this.ModuleSystem.modules[id])}
			{super.render(false)}
		</div>;
	}
}

ViewModule.Inputs = {
	Routes: {
		type: Module.Types.Object,
		defaultValue: {}
	}
}

ViewModule.Category = "Nikatlas";
ViewModule.EditPosition = "top-right";
export default ViewModule;