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')

@device.get('/')
def home():
    request: ContextId = ContextId()
    request.context_uuid.uuid = session['context_uuid']
    client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)
    response: DeviceList = client.ListDevices(request)
    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['context_uuid']
    client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)
    response: TopologyIdList = client.ListTopologyIds(request)
    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.extend([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.extend([int(driver)])
        try:
            client: DeviceClient = DeviceClient(DEVICE_SERVICE_ADDRESS, DEVICE_SERVICE_PORT)
            response: DeviceId = client.AddDevice(device)
            client.close()

            flash(f'New device was created with ID "{response.device_uuid.uuid}".', 'success')
            redirect('/device/')
        except Exception as e:
            print(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
    client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)
    response: Device = client.GetDevice(request)
    client.close()
    return render_template('device/detail.html', device=response)
