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

"""Website pages"""

# System modules
import json

# Third-party modules
from flask import Blueprint, render_template, request
from flask_httpauth import HTTPBasicAuth

# Custom modules
from utils.data_access_object import ObservationBlockObject as DAO

web = Blueprint('web', __name__)

dao = DAO("ob")
tpl = DAO("defaults")

auth = HTTPBasicAuth()
users_file = 'users.json'

try:
    with open(users_file) as json_file:
        users = json.load(json_file)
except FileNotFoundError as e:
    print(f"{users_file} containing user:pass not found")
    exit(0)

@auth.verify_password
def verify_password(username, password):
    if username in users and \
       users.get(username) == password:
        return username
    
@web.route("/")
@auth.login_required
def index():
    """Show all observation OB files"""
    data = {}
    return render_template("index.html", api_base_url=api_base_url)

@web.route("/init/")
@auth.login_required
def init():
    """Show the init page"""
    data = {}
    return render_template("init.html", data=data)

@web.route("/control/")
@auth.login_required
def control():
    """Show the control panel"""
    data = {}
    return render_template("control.html", data=data)

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

@web.route("/blocks/<string:name>/")
@auth.login_required
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)
    return render_template("block.html",
                           data=data, tpl=tpl.todos,
                           included=included)

@web.route("/blocks/<string:name>/<int:instance>/")
@auth.login_required
def blocks_name_instance(name, instance):
    """Show a specific template instance of the selected OB"""
    data = dao.show(name)
    data["content"] = [data["content"][instance]]
    return render_template("block.html", data=data)

@web.route("/sequencer/")
@auth.login_required
def bob():
    """Show the sequencer"""
    data = dao.todos
    return render_template("sequencer.html", data=data)

@web.route("/display/")
@auth.login_required
def display():
    """Show the display panel"""
    data = {}
    return render_template("display.html", data=data)

@web.route("/webcam/")
@auth.login_required
def webcam():
    """Show the webcam page"""
    data = {}
    return render_template("webcam.html", data=data)

@web.route("/webgl/")
@auth.login_required
def webgl():
    """Show the FITS in a webgl canvas"""
    data = {}
    return render_template("webgl.html", data=data)

@web.route("/environment/")
@auth.login_required
def environment():
    """ Display the meteo"""
    # from api.environment import Status
    # data = Status().get()
    data = {"external":{}, "internal":{}}

    exclude = ["Barometric_trend", "Battery_status", "Battery_volts",
               "ET_day", "ET_month", "ET_year",
               "Storm_start_date", "Forecast_rule_number", "Forecast_icon"
               ]

    for e in exclude:
        data["external"].pop(e, None)

    return render_template("meteo.html", data=data)

@web.route("/other/button/")
@auth.login_required
def other_button():
    """Show the help page"""
    data = {}
    return render_template("other/button.html", data=data)

@web.route("/other/fits/")
@auth.login_required
def other_fits():
    """download a fits"""
    # System modules
    import io

    # Third-party modules
    from flask import send_file

    with open("./temp.fits", mode='rb') as hdul:
        data = hdul.read()
        fitsdata = send_file(
            io.BytesIO(data),
            mimetype='image/fits',
            as_attachment=False,
            #download_name='ciccio.fits'
        )

    return fitsdata

@web.route("/testfulvio/test/")
def testfulvio():
    """GET fulvio test web page."""
    data = {}
    return render_template("other/fulvio.html", data=data)
