from pypdevs.DEVS import CoupledDEVS
from atomic import *
from events import Ship
import pandas as pd

class Port(CoupledDEVS):
	def __init__(self, name, plan, layer=None):
		super(Port, self).__init__(name)

		self.planner = self.addSubModel(Planner("planner", plan, layer))
		self.pool = self.addSubModel(Pool("pool"))
		self.sail = self.addSubModel(Sailer("sail", 6.235, 4.165)) # TODO: use the values from the data
		self.tugs = self.addSubModel(Sailer("tugs", 4.455, 2.001))

		self.connectPorts(self.planner.reqs, self.pool.req_in)
		self.connectPorts(self.pool.ship_out_sail, self.sail.ship_in)
		self.connectPorts(self.pool.ship_out_tug, self.tugs.ship_in)
		self.connectPorts(self.sail.ship_out, self.pool.ship_in)
		self.connectPorts(self.tugs.ship_out, self.pool.ship_in)

	def select(self, imm_children):
		for child in imm_children:
			if isinstance(child, Sailer):
				return child
		for child in imm_children:
			if isinstance(child, Pool):
				return child
		return imm_children[0]


if __name__ == '__main__':
	from mapper import PoABLayer

	data = pd.read_csv("2022.csv")
	data = data.sort_values('time')

	layer = PoABLayer()

	port = Port("port", data, layer)
	set = {}
	for ix, row in data.iterrows():
		if row["Sleepboot"] not in set:
			set[row["Sleepboot"]] = row["Locatie van"]
	for b, l in set.items():
		port.pool.state["ships"][b] = Ship(b, l, 0, 0, 0, 0)

	import geoplotlib
	geoplotlib.set_window_size(640, 760)
	geoplotlib.tiles_provider({
		'url': lambda zoom, xtile, ytile: 'http://a.tile.stamen.com/terrain/%d/%d/%d.png' % (zoom, xtile, ytile),
		'tiles_dir': 'mytiles',
		'attribution': 'Map tiles by Stamen Design, under CC BY 3.0. Data @ OpenStreetMap contributors.'
	})

	geoplotlib.add_layer(layer)

	from pypdevs.simulator import Simulator
	sim = Simulator(port)
	sim.setClassicDEVS()
	sim.setRealTime()
	# sim.setVerbose(None)
	sim.setTerminationTime(1000)
	sim.simulate()

	geoplotlib.show()