import os
import json
from jinja2 import Environment, FileSystemLoader
from server.model import Session, IO


def generate_html(io_id):
    session = Session()
    io = session.query(IO).filter_by(id=io_id).first()
    doors = io.doors

    inputs_map = dict(pair for d in list(map(lambda d: { d.in_pin: 0 }, doors)) for pair in d.items())
    outputs_map = dict(pair for d in list(map(lambda d: { d.out_pin: 0 }, doors)) for pair in d.items())
    delays_map = dict(pair for d in list(map(lambda d: { d.out_pin: d.delay }, doors)) for pair in d.items())
    nonc_map = dict(pair for d in list(map(lambda d: { d.in_pin: d.nonc }, doors)) for pair in d.items())
    input_pins = list(map(lambda d: d.in_pin, doors))
    output_pins = list(map(lambda d: d.out_pin, doors))
    door_names = list(map(lambda d: d.name, doors))

    j2_env = Environment(
        loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
        trim_blocks=True)

    return j2_env.get_template('template.html').render(
        layout_id=io.id,
        layout_name=io.name,
        inputs_map=json.dumps(inputs_map),
        outputs_map=json.dumps(outputs_map),
        delays_map=json.dumps(delays_map),
        nonc_map=json.dumps(nonc_map),
        input_pins=input_pins,
        output_pins=output_pins,
        door_names=door_names,
        mode=io.state)
