##  CODE SET UP TO BE RUN FROM EXEC_ALL.PY

from flask import Flask, send_from_directory, render_template, request, redirect, url_for
import sqlite3
import variables_module
import folium 

# declare Flask with custom folder directories
app = Flask(__name__, template_folder='../Website', static_folder='../Website')


# LOGIN PAGE CODE

# render login page
@app.route('/')
def update_index_page():
        return render_template('index.html')


# fetch login page from directory
@app.route('/login.html')
def serve_html_index():
    return send_from_directory(app.template_folder, 'index.html')


# fetch login page css to render it with the page
@app.route('/style.css')
def serve_css_style():
    return send_from_directory(app.static_folder, 'style.css')


# user login and password details
credentials = {
    "admin": "qwerty",
    "test": "password"
}


# converted Javascript code to Python Flask to verify user details and switch to different page
@app.route('/login', methods=['POST'])
def login():
    # fetch details from html form
    username = request.form.get('username')
    password = request.form.get('password')

    # Check if the username exists in the credentials dictionary
    if username in credentials and credentials[username] == password:
        # Redirect to the device page upon successful login
        return redirect(url_for('update_page'))
    else:
        # Render the login page with an error message
        return render_template('index.html', error="Invalid username or password")

# TEMP_SENSORS PAGE

# SQL query to fetch required data for temp_sensors page
def fetch_web_data(cursor):
    cursor.execute("""SELECT ts.LOCATION,
                          ts.DATE,
                          strftime('%H:%M:%S', ts.TIME),
                          ts.TEMPERATURE,
                          CASE
                                WHEN h.STATUS = 1 THEN 'ON'
                                ELSE 'OFF'
                          END
                          FROM temperature_sensors ts
                          JOIN heating_central h ON ts.ID = h.ID
                          ORDER BY ts.DATE DESC,ts.TIME DESC
                          LIMIT 7;""")
    return cursor.fetchall()

# function which renders a temp_sensors page and fetch SQL query data and places data on page based on keys


# function which renders a temp_sensors page and fetch SQL query data and places data on page based on keys
@app.route('/temp_sensors.html')
def update_page():
        connect_db = sqlite3.connect('Database/database.db')
        cursor = connect_db.cursor()
        data = fetch_web_data(cursor)
        connect_db.commit()  # commit changes to database
        connect_db.close()  # close database
        return render_template(
                                'temp_sensors.html',
                                location_1=data[0][0],
                                time_1=data[0][2],
                                temperature_1=data[0][3],
                                heater_1=data[0][4],
                                location_2=data[1][0],
                                time_2=data[1][2],
                                temperature_2=data[1][3],
                                heater_2=data[1][4],
                                location_3=data[2][0],
                                time_3=data[2][2],
                                temperature_3=data[2][3],
                                heater_3=data[2][4],
                                location_4=data[3][0],
                                time_4=data[3][2],
                                temperature_4=data[3][3],
                                heater_4=data[3][4],
                                location_5=data[4][0],
                                time_5=data[4][2],
                                temperature_5=data[4][3],
                                heater_5=data[4][4],
                                location_6=data[5][0],
                                time_6=data[5][2],
                                temperature_6=data[5][3],
                                heater_6=data[5][4],
                                location_7=data[6][0],
                                time_7=data[6][2],
                                temperature_7=data[6][3],
                                heater_7=data[6][4]
                                   )

# fetch temp_sensors css to render it with the page
@app.route('/temp_sensors.css')
def serve_css_temp():
    return send_from_directory(app.static_folder, 'temp_sensors.css')

@app.route('/reload')
def reload():
    return redirect(url_for('update_page'))

@app.route('/digital.ttf')
def serve_font_meter():
    return send_from_directory(app.static_folder, 'digital.ttf')

@app.route('/Heat.ttf')
def serve_font_temp_title():
    return send_from_directory(app.static_folder, 'Heat.ttf')

from variables_module import max_temperature, min_temperature
@app.route('/change_temp', methods=['POST'])
def change_temp():
    # fetch details from html form
    max_temp = request.form.get('max_temp')
    min_temp = request.form.get('min_temp')

    #
    if max_temp.isdigit() and min_temp.isdigit():
        variables_module.max_temperature = max_temp
        variables_module.min_temperature = min_temp
        return redirect(url_for('update_page'))

    else:
        # Render the login page with an error message
        return render_template('temp_sensors.html', error="Invalid input type")

# HEADER AND FOOTER
# fetch header and footer css to render it with the page
@app.route('/frame.css')
def serve_css_frame():
    return send_from_directory(app.static_folder, 'frame.css')

# fetch logo to render it with the page
@app.route('/logo.png')
def serve_logo():
    return send_from_directory(app.static_folder, 'logo.png')

# fetches fonts to render them with the page
@app.route('/OTF.otf')
def serve_font_title():
    return send_from_directory(app.static_folder, 'OTF.otf')

@app.route('/drop_font.otf')
def serve_font_drop():
    return send_from_directory(app.static_folder, 'drop_font.otf')

# main loop
def main():

    app.run(host='localhost', port=4999)     # run Flask with host = 'localhost', port = 5000 to match webview window

main()