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

from sqlalchemy import Column, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from typing import Dict
from ._Base import _Base

class LinkModel(_Base):
    __tablename__ = 'link'

    link_uuid  = Column(UUID(as_uuid=False), primary_key=True)
    link_name  = Column(String, nullable=False)
    created_at = Column(DateTime, nullable=False)
    updated_at = Column(DateTime, nullable=False)

    #topology_links = relationship('TopologyLinkModel', back_populates='link')
    link_endpoints = relationship('LinkEndPointModel') # lazy='joined', back_populates='link'

    def dump_id(self) -> Dict:
        return {'link_uuid': {'uuid': self.link_uuid}}

    def dump(self) -> Dict:
        return {
            'link_id'          : self.dump_id(),
            'name'             : self.link_name,
            'link_endpoint_ids': [
                link_endpoint.endpoint.dump_id()
                for link_endpoint in self.link_endpoints
            ],
        }

class LinkEndPointModel(_Base):
    __tablename__ = 'link_endpoint'

    link_uuid     = Column(ForeignKey('link.link_uuid',         ondelete='CASCADE' ), primary_key=True)
    endpoint_uuid = Column(ForeignKey('endpoint.endpoint_uuid', ondelete='RESTRICT'), primary_key=True, index=True)

    link     = relationship('LinkModel',     back_populates='link_endpoints', lazy='joined')
    endpoint = relationship('EndPointModel', lazy='joined') # back_populates='link_endpoints'
