import configparser
from de2.elements import Port
from pypdevs.simulator import Simulator

config = configparser.ConfigParser()
config.read('config.ini')

tugging = config.getfloat('movement', 'velocity_mean_tugging'), config.getfloat('movement', 'velocity_std_tugging')
sailing = config.getfloat('movement', 'velocity_mean_sailing'), config.getfloat('movement', 'velocity_std_sailing')
vel_max = config.getfloat('movement', 'velocity_max')
if config.getboolean('movement', 'use_eta'):
	tugging = sailing = vel_max = None

port = Port("PoAB", config.get('simulation', 'schedule_file'), tugging, sailing, vel_max)

sim = Simulator(port)
if config.getboolean('simulation', 'verbose'):
	sim.setVerbose(None)
end_time = config.getfloat('simulation', 'end_time')
if end_time > 0:
	sim.setTerminationCondition(lambda t, m: t[0] > end_time or m.scheduler.state["index"] >= len(m.scheduler.ivef))
else:
	sim.setTerminationCondition(lambda _, m: m.scheduler.state["index"] >= len(m.scheduler.ivef))

timescale = config.getfloat('simulation', 'timescale')
if timescale > 0:
	sim.setRealTime(scale=timescale)

if config.getboolean('simulation', 'visualization') and timescale > 0:
	from de2.tracer import Streamer
	import geoplotlib
	from mapper import PoABLayer

	streamer = Streamer()
	sim.setCustomTracer("de2.tracer", "TracerPort", [streamer])
	layer = PoABLayer(sim, streamer)

	geoplotlib.set_window_size(640, 760)
	geoplotlib.tiles_provider({
	    'url': lambda zoom, xtile, ytile: 'https://tile.openstreetmap.org/%d/%d/%d.png' % (zoom, xtile, ytile),
	    'tiles_dir': 'mytiles',
	    'attribution': 'Map tiles by OpenStreetMap Carto, under CC BY 3.0. Data @ OpenStreetMap contributors.'
	})

	geoplotlib.add_layer(layer)
	geoplotlib.show()
else:
	sim.simulate()

if config.getboolean('simulation', 'statistics'):
	sim.model.print_statistics()