# 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.

import time
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy_cockroachdb import run_transaction
from typing import Dict, List, Optional, Set, Tuple
from common.proto.context_pb2 import Link, LinkId, LinkIdList, LinkList
from common.rpc_method_wrapper.ServiceExceptions import NotFoundException
from context.service.database.models.LinkModel import LinkModel
from context.service.database.models.RelationModels import LinkEndPointModel, TopologyLinkModel

def link_list_ids(db_engine : Engine) -> LinkIdList:
    def callback(session : Session) -> List[Dict]:
        obj_list : List[LinkModel] = session.query(LinkModel).all()
        #.options(selectinload(LinkModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump_id() for obj in obj_list]
    return LinkIdList(link_ids=run_transaction(sessionmaker(bind=db_engine), callback))

def link_list_objs(db_engine : Engine) -> LinkList:
    def callback(session : Session) -> List[Dict]:
        obj_list : List[LinkModel] = session.query(LinkModel).all()
        #.options(selectinload(LinkModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump() for obj in obj_list]
    return LinkList(links=run_transaction(sessionmaker(bind=db_engine), callback))

def link_get(db_engine : Engine, request : LinkId) -> Link:
    link_uuid = request.link_uuid.uuid
    def callback(session : Session) -> Optional[Dict]:
        obj : Optional[LinkModel] = session.query(LinkModel)\
            .filter_by(link_uuid=link_uuid).one_or_none()
        return None if obj is None else obj.dump()
    obj = run_transaction(sessionmaker(bind=db_engine), callback)
    if obj is None: raise NotFoundException('Link', link_uuid)
    return Link(**obj)

def link_set(db_engine : Engine, request : Link) -> bool:
    link_uuid = request.link_id.link_uuid.uuid
    link_name = request.name

    topology_keys : Set[Tuple[str, str]] = set()
    related_topologies : List[Dict] = list()
    link_endpoints_data : List[Dict] = list()
    for endpoint_id in request.link_endpoint_ids:
        context_uuid  = endpoint_id.topology_id.context_id.context_uuid.uuid
        topology_uuid = endpoint_id.topology_id.topology_uuid.uuid
        device_uuid   = endpoint_id.device_id.device_uuid.uuid
        endpoint_uuid = endpoint_id.endpoint_uuid.uuid

        link_endpoints_data.append({
            'link_uuid'    : link_uuid,
            'context_uuid' : context_uuid,
            'topology_uuid': topology_uuid,
            'device_uuid'  : device_uuid,
            'endpoint_uuid': endpoint_uuid,
        })

        if len(context_uuid) > 0 and len(topology_uuid) > 0:
            topology_key = (context_uuid, topology_uuid)
            if topology_key not in topology_keys:
                related_topologies.append({
                    'context_uuid': context_uuid,
                    'topology_uuid': topology_uuid,
                    'link_uuid': link_uuid,
                })
                topology_keys.add(topology_key)

    def callback(session : Session) -> None:
        obj : Optional[LinkModel] = session.query(LinkModel).with_for_update()\
            .filter_by(link_uuid=link_uuid).one_or_none()
        is_update = obj is not None
        if is_update:
            obj.link_name = link_name
            session.merge(obj)
        else:
            session.add(LinkModel(link_uuid=link_uuid, link_name=link_name, created_at=time.time()))
        obj : Optional[LinkModel] = session.query(LinkModel)\
            .filter_by(link_uuid=link_uuid).one_or_none()

        stmt = insert(LinkEndPointModel).values(link_endpoints_data)
        stmt = stmt.on_conflict_do_nothing(
            index_elements=[
                LinkEndPointModel.link_uuid, LinkEndPointModel.context_uuid, LinkEndPointModel.topology_uuid,
                LinkEndPointModel.device_uuid, LinkEndPointModel.endpoint_uuid
            ],
        )
        session.execute(stmt)

        session.execute(insert(TopologyLinkModel).values(related_topologies).on_conflict_do_nothing(
            index_elements=[
                TopologyLinkModel.context_uuid, TopologyLinkModel.topology_uuid,
                TopologyLinkModel.link_uuid
            ]
        ))
    run_transaction(sessionmaker(bind=db_engine), callback)
    return False # TODO: improve and check if created/updated

def link_delete(db_engine : Engine, request : LinkId) -> bool:
    link_uuid = request.link_uuid.uuid
    def callback(session : Session) -> bool:
        session.query(TopologyLinkModel).filter_by(link_uuid=link_uuid).delete()
        session.query(LinkEndPointModel).filter_by(link_uuid=link_uuid).delete()
        num_deleted = session.query(LinkModel).filter_by(link_uuid=link_uuid).delete()
        #db_link = session.query(LinkModel).filter_by(link_uuid=link_uuid).one_or_none()
        #session.query(LinkModel).filter_by(link_uuid=link_uuid).delete()
        return num_deleted > 0
    return run_transaction(sessionmaker(bind=db_engine), callback)
