# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008-2017,2019  Contributor
#
# 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.
""" How we represent location data in Aquilon """

from datetime import datetime

from sqlalchemy import (Integer, DateTime, Sequence, String, Column,
                        ForeignKey, UniqueConstraint, PrimaryKeyConstraint,
                        Index)
from sqlalchemy import literal
from sqlalchemy.orm import (relation, backref, object_session, deferred,
                            reconstructor)
from sqlalchemy.sql import and_, or_, desc

from aquilon.aqdb.model import Base, DnsDomain
from aquilon.aqdb.column_types import AqStr
from aquilon.exceptions_ import AquilonError


class Location(Base):
    """ How we represent location data in Aquilon """
    __tablename__ = 'location'

    valid_parents = []

    id = Column(Integer, Sequence('location_id_seq'), primary_key=True)

    name = Column(AqStr(16), nullable=False)

    location_type = Column(AqStr(32), nullable=False)

    fullname = Column(String(255), nullable=False)

    default_dns_domain_id = Column(ForeignKey(DnsDomain.id,
                                              ondelete='SET NULL'),
                                   nullable=True)

    creation_date = deferred(Column(DateTime, default=datetime.now,
                                    nullable=False))

    comments = Column(String(255), nullable=True)

    default_dns_domain = relation(DnsDomain)

    uri = Column(String(255), nullable=True)

    __table_args__ = (UniqueConstraint(name, location_type),
                      Index("location_dns_domain_idx",
                            default_dns_domain_id),
                      {'info': {'unique_fields': ['name', 'location_type']}},)
    __mapper_args__ = {'polymorphic_on': location_type}

    def __getattr__(self, name):
        if name in self.__mapper__.polymorphic_map:
            return self.get_p_dict(name)

        raise AttributeError("'%s' object has no attribute '%s'" %
                             (self.__class__.__name__, name))  # pragma: no cover

    def get_p_dict(self, loc_type):
        if self._parent_dict is None:
            self._parent_dict = {str(self.location_type): self}
            for node in self.parents:
                self._parent_dict[str(node.location_type)] = node
        return self._parent_dict.get(loc_type, None)

    def offspring_ids(self):
        session = object_session(self)
        q = session.query(Location.id)
        q = q.join((LocationLink, Location.id == LocationLink.child_id))
        # Include self as well
        q = q.filter(or_(Location.id == self.id,
                         LocationLink.parent_id == self.id))
        return q.subquery()

    def parent_ids(self):
        session = object_session(self)
        q = session.query(Location.id)
        q = q.join((LocationLink, Location.id == LocationLink.parent_id))
        # Include self as well
        q = q.filter(or_(Location.id == self.id,
                         LocationLink.child_id == self.id))
        return q.subquery()

    def sysloc(self):
        components = ('building', 'city', 'continent')
        names = []
        for component in components: