# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.

import json, logging, operator, requests
from requests.auth import HTTPBasicAuth
from typing import Optional
from device.service.driver_api._Driver import RESOURCE_ENDPOINTS, RESOURCE_SERVICES

LOGGER = logging.getLogger(__name__)

HTTP_OK_CODES = {
    200,    # OK
    201,    # Created
    202,    # Accepted
    204,    # No Content
}

def find_key(resource, key):
    return json.loads(resource[1])[key]

def get_lightpaths(root_url : str, resource_key : str,auth : Optional[HTTPBasicAuth] = None,
                   timeout : Optional[int] = None):
    headers = {'accept': 'application/json'}
    url = '{:s}/OpticalTFS/GetLightpaths'.format(root_url)

    result = []
    try:
        response = requests.get(url, timeout=timeout, headers=headers, verify=False, auth=auth)
    except requests.exceptions.Timeout:
        LOGGER.exception('Timeout connecting {:s}'.format(url))
        return result
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.exception('Exception retrieving {:s}'.format(resource_key))
        result.append((resource_key, e))
        return result

    try:
        flows = json.loads(response.content)
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.warning('Unable to decode reply: {:s}'.format(str(response.content)))
        result.append((resource_key, e))
        return result

    # if resource_key == RESOURCE_ENDPOINTS:
    for flow in flows:
        flow_id = flow.get('flow_id')
        source = flow.get('src')
        destination = flow.get('dst')
        bitrate = flow.get('bitrate')
        # more TODO

        endpoint_url = '/flows/flow[{:s}]'.format(flow_id)
        endpoint_data = {'flow_id': flow_id, 'src': source, 'dst': destination, 'bitrate': bitrate}
        result.append((endpoint_url, endpoint_data))

    return result


def add_lightpath(root_url, src_node, dst_node, bitrate,
                   auth : Optional[HTTPBasicAuth] = None, timeout : Optional[int] = None):
        
    headers = {'accept': 'application/json'}
    # url = '{:s}/OpticalTFS/AddLightpath/{:s}/{:s}/{:s}'.format(root_url, src_node, dst_node, bitrate)

    results = []
    try:
        LOGGER.info('Lightpath request: {:s} <-> {:s} with {:s} bitrate'.format(
            str(src_node), str(dst_node), str(bitrate)))
        
        device1= 'T1'
        ep1= 'ep1'
        device2= 'T2'
        ep2= 'ep2'
        context_uuid = 'admin'
        service_uuid = 'T1-T2_service'

        data = {
        "services": [
            {
                "service_id": {
                    "context_id": {"context_uuid": {"uuid": context_uuid}}, "service_uuid": {"uuid": service_uuid}
                },
                "service_type": 5,
        }
        ]
        }
        url = '{:s}'.format(root_url) + '/context/{:s}/service/{:s}'.format(context_uuid, service_uuid)
        response = requests.post(url=url, timeout=timeout, headers=headers, verify=False, auth=auth, data=json.dumps(data)).json()


        data = {
        "services": [
            {
                "service_id": {
                    "context_id": {"context_uuid": {"uuid": "admin"}}, "service_uuid": {"uuid": "service_uuid"}
                },
                "service_type": 5,
                "service_status": {"service_status": 1},
                "service_endpoint_ids": [
                    {"device_id":{"device_uuid":{"uuid":device1}},"endpoint_uuid":{"uuid":ep1}},
                    {"device_id":{"device_uuid":{"uuid":device2}},"endpoint_uuid":{"uuid":ep2}}
                ],
                "service_config": {"config_rules": [
                    {"action": 1, "custom": {"resource_key": "/settings", "resource_value": {
                    }}
            }
        ]
        }
        }
        ]
        }
        url = '{:s}'.format(root_url) + '/context/{:s}/service/{:s}'.format(context_uuid, service_uuid)
        response = requests.put(url=url, timeout=timeout, headers=headers, verify=False, auth=auth, data=json.dumps(data))


        #response = requests.put(url=url, timeout=timeout, headers=headers, verify=False, auth=auth)
        results.append(response.json())
        LOGGER.info('Response: {:s}'.format(str(response)))
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.exception('Exception requesting Lightpath: {:s} <-> {:s} with {:s} bitrate'.format(
            str(src_node), str(dst_node), str(bitrate)))
        results.append(e)
    else:
        if response.status_code not in HTTP_OK_CODES:
            msg = 'Could not create Lightpath(status_code={:s} reply={:s}'
            LOGGER.error(msg.format(str(response.status_code), str(response)))
        results.append(response.status_code in HTTP_OK_CODES)
    
    return results



def del_lightpath(root_url, flow_id, src_node, dst_node, bitrate,
                   auth : Optional[HTTPBasicAuth] = None, timeout : Optional[int] = None):
    url = '{:s}/OpticalTFS/DelLightpath/{:s}/{:s}/{:s}/{:s}'.format(root_url, flow_id, src_node, dst_node, bitrate)
    headers = {'accept': 'application/json'}

    results = []

    try:
        response = requests.delete(url=url, timeout=timeout, headers=headers, verify=False, auth=auth)
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.exception('Exception deleting Lightpath(uuid={:s})'.format(str(flow_id)))
        results.append(e)
    else:
        if response.status_code not in HTTP_OK_CODES:
            msg = 'Could not delete Lightpath(flow_id={:s}). status_code={:s} reply={:s}'
            LOGGER.error(msg.format(str(flow_id), str(response.status_code), str(response)))
        results.append(response.status_code in HTTP_OK_CODES)

    return results


def get_topology(root_url : str, resource_key : str,auth : Optional[HTTPBasicAuth] = None,
                   timeout : Optional[int] = None):
    headers = {'accept': 'application/json'}
    url = '{:s}/OpticalTFS/GetLinks'.format(root_url)

    result = []
    try:
        response = requests.get(url, timeout=timeout, headers=headers, verify=False, auth=auth)
    except requests.exceptions.Timeout:
        LOGGER.exception('Timeout connecting {:s}'.format(url))
        return result
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.exception('Exception retrieving {:s}'.format(resource_key))
        result.append((resource_key, e))
        return result

    try:
        links = json.loads(response.content)
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.warning('Unable to decode reply: {:s}'.format(str(response.content)))
        result.append((resource_key, e))
        return result

    # if resource_key == RESOURCE_ENDPOINTS:
    #for link in links:
        # TODO

        # endpoint_url = '/flows/flow[{:s}]'.format(flow_id)
        # endpoint_data = {'flow_id': flow_id, 'src': source, 'dst': destination, 'bitrate': bitrate}
        # result.append((endpoint_url, endpoint_data))

    return result
