#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""SHARK-NIR Website pages"""

# System modules
import json
import os

# Third-party modules
from flask import Blueprint, render_template, request
from flask import send_file, abort

# Custom modules
from util.instances import seq, sch, dao, tpl, ref, doc, deo, RTC

web = Blueprint('web', __name__)

def merge(device=None):

    status = deo.readall()
    options = sch.read("InstrumentSetup")

    opt_devs =  { o["name"]: o for o in options if o["name"] in status}

    for dev,val in opt_devs.items():
        opt_devs[dev]["status"] = status[dev]

    return opt_devs


def fill_params(params_all, s, def_or_ref="def"):

    opts = { o["name"]: o for o in sch.read(s) } # dict

    if params_all and (s in params_all) and params_all[s]:
         params = params_all[s]
    else:
        return []

    params_and_opts = []
    for k,v in params.items():
        for a,b in opts.items():
            if a==k:
                full_params = dict({"value":v, "type":def_or_ref}.items() + b.items())
                print(json.dumps(full_params, indent=4))
                params_and_opts.append(full_params)

    params_and_opts = sorted(params_and_opts, key=lambda k: k['name'])
    return params_and_opts

#######
# Pages
#######

@web.route("/")
def index():
    """First page"""
    data = {}
    return render_template("index.html", data=data)

@web.route("/home/")
def homeWeb():
    """Show the home page"""
    return render_template("index.html")

@web.route("/sequencer")
def bobWeb():
    data = sorted(dao.todos)
    return render_template("sequencer.html", data=data)

@web.route("/devices")
def deviceListWeb():
    """Show SHARK devices in a web page """
    data = merge()
    return render_template("devices.html", devices=data)

###########
# OB editor
###########

@web.route("/blocks/")
def blocks():
    """Show all observation OB files"""
    data = sorted(dao.todos)
    return render_template("blocks.html", data=data)


@web.route("/blocks/<string:name>/")
def blocks_name(name):
    """Show a selected OB, update it, or add a new
    template in it.
    """

    included = request.args.get("included") or False
    data = dao.show(name)

    documentation = "No documentation"

    if data and "Template" in data and data["Template"]:
        for template in data["Template"]:
            defs_all = template
            refs_all = ref.read(template["TPLID"]) # takes the file
            documentation = doc.read(template["TPLID"])
            # try:
            #     template.update({"doc":documentation})
            #     print("update worked! ")
            # except Exception as e:
            #     print("Errore in update")
            #     print(e)
                
            for subsystem in sch.schemas:
                defs_filled = fill_params(defs_all, subsystem)
                refs_filled = fill_params(refs_all, subsystem, def_or_ref="ref")
                template[subsystem] = defs_filled + refs_filled

    #print(data)
    return render_template("block.html", data=data, tpl=tpl.todos,
                           doc=documentation, included=included)


###########
# RTC panel
###########

RTC.create({"name": "CRED2 image",
            "id":   "cred",
            "info": [
                ("min", "image min (counts)"),
                ("max", "image max (counts)"),
                ("tot_flux", "8x8 around rtc centr (counts/frame)"),
                ]
            })

RTC.create({"name": "Mirror shape",
            "id":   "dm",
            "info": [
                ("min", "actuator min"),
                ("max", "actuator max"),
                ("skp_cmd", "# skipped comands")
                ]
            })

RTC.create({"name": "Mirror shape without flat",
            "id":   "dm2",
            "info": [
                ("min", "actuator min"),
                ("max", "actuator max"),
                ]
            })

RTC.create({"name": "Centroid cloud",
            "id":   "cloud",
            "info": [
                ("min", "histo min (counts)"),
                ("max", "histo max (counts)"),
                ("wx", "PtV x (mas)"),
                ("wy", "PtV y (mas)"),
                ("RMS_X", "RMS x (mas)"),
                ("RMS_Y", "RMS y (mas)"),
                ("cloud_samples", "Samples (#)"),
                ]
            })

@web.route("/rtc")
def rtcTest():
    data = RTC.todos
    darks = RTC.todos_dark()
    gains = RTC.todos_gain()
    flats = RTC.todos_flat()
    ncpas = RTC.todos_ncpa()
    return render_template("rtc.html", data=data, darks=darks,
                                         flats=flats, gains=gains, ncpas=ncpas)

###########
# Tests
###########

@web.route("/webgl")
def webglTest():
    data = {}
    return render_template("webgl.html", data=data)

@web.route("/tel")
def telTest():
    data = {}
    return render_template("tel.html", data=data)

@web.route('/simbad', methods=["POST"])
def simbad():
    from util import functions as ufun
    req = request.json
    print(req)
    table = ufun.query_simbad_coordinates(str(req))
    print(table)
    res = ufun.table_to_python(table)
    return res
