"""Functions to act as service for adding devices to database"""

from jsonschema import validate, ValidationError
from src.in_io import sqlite as pysql
from src.http.schema.inator_schemas import JSON_SCHEMA


def validate_devices(devices_json):
    """Validates device JSON. Returns (json_data, error) tuple."""
    json_data = {"devices": devices_json}
    try:
        validate(instance=json_data, schema=JSON_SCHEMA)
    except ValidationError as e:
        return None, e.message
    return json_data, None


def save_devices_to_db(cursor, connection, devices_json):
    """Insert devices and sensors into the database."""
    for device in devices_json:
        device_id = pysql.insert_dev_table(cursor, device)
        if not device_id:
            return False
        pysql.create_dev_info_table(cursor, device_id, device)
        pysql.create_dev_log_table(cursor, device_id, device)
        for sensor in device["sensors"]:
            pysql.insert_dev_info_table(cursor, device_id, device, sensor)

    connection.commit()
    connection.close()
    return True
