# Endpoints for user to control the home.


from datetime import datetime
from flask import Blueprint, jsonify, request
from services import elements_services, home_services

home_api = Blueprint('/home_api', __name__)
elements_services = elements_services.ElementsServices()
home_services = home_services.HomeServices()


@home_api.route('/profiles')
def profiles():
    """Gets all profiles for all elements for user application to display and manipulate elements"""
    return jsonify(home_services.get_profiles())


@home_api.route('/element', methods=['POST'])
def update_element():
    """Updates single element with all new values received from the user application"""
    received_element = request.get_json()
    home_services.update_element(received_element)
    return 'OK'


@home_api.route('/elements', methods=['POST'])
def update_elements():
    """Updates all elements with all new values received from the user application"""
    received_elements = request.get_json()
    home_services.update_elements(received_elements)
    return 'OK'


@home_api.route('/elementdelete', methods=['POST'])
def delete_element():
    """Deletes a single element with given hid"""
    element = request.get_json()
    home_services.delete_element(element['hid'])
    return 'OK'


@home_api.route('/timerules', methods=['POST'])
def timerules():
    """Adds, Updates or deletes time rule for the given element"""
    rules = request.get_json()

    if len(rules) == 0:
        raise Exception("No elements in the list")

    for rule in rules:
        if 'id' not in rule:
            rule['id'] = None

    home_services.save_time_rules(rules)
    return 'OK'

@home_api.route('/timerules/<string:hid>')
def get_timerules(hid):
    """Gets list of timerules for given hid"""
    timerules= home_services.read_time_rules(hid)
    return jsonify(timerules)
