# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from flask import render_template, Blueprint, flash, session, redirect
from device.client.DeviceClient import DeviceClient
from context.client.ContextClient import ContextClient
from webui.Config import (CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT,
                DEVICE_SERVICE_ADDRESS, DEVICE_SERVICE_PORT)
from webui.proto.context_pb2 import (ContextId, DeviceList, DeviceId,
    Device, DeviceDriverEnum, DeviceOperationalStatusEnum,
    ConfigActionEnum, ConfigRule, TopologyIdList, TopologyList)
from webui.service.device.forms import AddDeviceForm

device = Blueprint('device', __name__, url_prefix='/device')
context_client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)
device_client: DeviceClient = DeviceClient(DEVICE_SERVICE_ADDRESS, DEVICE_SERVICE_PORT)

@device.get('/')
def home():
    request: ContextId = ContextId()
    request.context_uuid.uuid = session.get('context_uuid', '-')
    context_client.connect()
    response: DeviceList = context_client.ListDevices(request)
    context_client.close()
    return render_template('device/home.html', devices=response.devices,
                                               dde=DeviceDriverEnum,
                                               dose=DeviceOperationalStatusEnum)

@device.route('add', methods=['GET', 'POST'])
def add():
    form = AddDeviceForm()

    request: ContextId = ContextId()
    request.context_uuid.uuid = session.get('context_uuid', '-')
    context_client.connect()
    response: TopologyIdList = context_client.ListTopologyIds(request)
    context_client.close()

    # listing enum values
    form.operational_status.choices = [(-1, 'Select...')]
    for key, value in DeviceOperationalStatusEnum.DESCRIPTOR.values_by_name.items():
        form.operational_status.choices.append((DeviceOperationalStatusEnum.Value(key), key.replace('DEVICEOPERATIONALSTATUS_', '')))
    
    # device driver ids
    device_driver_ids = []
    for key in DeviceDriverEnum.DESCRIPTOR.values_by_name:
        device_driver_ids.append(f"{DeviceDriverEnum.Value(key)}={key.replace('DEVICEDRIVER_', '')}")
    device_driver_ids = ', '.join(device_driver_ids)

    if form.validate_on_submit():
        device: Device = Device()
        device.device_id.device_uuid.uuid = form.device_id.data
        device.device_type = form.device_type.data
        if '\n' not in form.device_config.data:
            data = form.device_config.data.strip() + '\n'
        else:
            data = form.device_config.data.strip()
        
        for config in data.split('\n'):
            if len(config.strip()) > 0:
                parts = config.strip().split('=')
                config_rule: ConfigRule = ConfigRule()
                config_rule.action = ConfigActionEnum.CONFIGACTION_SET
                config_rule.resource_key = parts[0].strip()
                config_rule.resource_value = parts[1].strip()
                device.device_config.config_rules.append(config_rule)

        device.device_operational_status = form.operational_status.data

        if ',' not in form.device_drivers.data:
            data = form.device_drivers.data.strip() + ','
        else:
            data = form.device_drivers.data.strip()
        
        for driver in data.split(','):
            driver = driver.strip()
            if len(driver) == 0:
                continue
            device.device_drivers.append(int(driver))
        try:
            device_client.connect()
            response: DeviceId = device_client.AddDevice(device)
            device_client.close()

            flash(f'New device was created with ID "{response.device_uuid.uuid}".', 'success')
            return redirect('/device/')
        except Exception as e:
            flash(f'Problem adding the device. {e.details()}', 'danger')
        
    return render_template('device/add.html', form=form,
                    submit_text='Add New Device',
                    device_driver_ids=device_driver_ids)

@device.route('detail/<device_uuid>', methods=['GET', 'POST'])
def detail(device_uuid: str):
    request: DeviceId = DeviceId()
    request.device_uuid.uuid = device_uuid
    context_client.connect()
    response: Device = context_client.GetDevice(request)
    context_client.close()
    return render_template('device/detail.html', device=response)

@device.get('<device_uuid>/delete')
def delete(device_uuid):
    try:

        # first, check if device exists!
        # request: DeviceId = DeviceId()
        # request.device_uuid.uuid = device_uuid
        # response: Device = client.GetDevice(request)
        # TODO: finalize implementation

        request: DeviceId = DeviceId()
        request.device_uuid.uuid = device_uuid
        device_client.connect()
        response = device_client.DeleteDevice(request)

        device_client.close()

        flash('Device deleted successfully!', 'success')
    except Exception as e:
        flash(f'Problem deleting the device. {e.details()}', 'danger')

    return redirect('/device/')
