# -*- coding: utf-8 -*-

# Copyright (C) 2018 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

from sqlalchemy.schema import Column, PrimaryKeyConstraint, ForeignKeyConstraint, Index, Sequence
from sqlalchemy.types import Integer, String, Text, Boolean, Date
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy import text

from xivo_dao.alchemy.preferred_callback_period import PreferredCallbackPeriod
from xivo_dao.alchemy.callback_list import CallbackList
from xivo_dao.helpers.db_manager import Base


class CallbackRequest(Base):

    __tablename__ = 'callback_request'
    __table_args__ = (
        PrimaryKeyConstraint('uuid'),
        ForeignKeyConstraint(('list_uuid',),
                             ('callback_list.uuid',),),
        ForeignKeyConstraint(('preferred_callback_period_uuid',),
                             ('preferred_callback_period.uuid',),),
        Index('callback_request__idx_reference_number', 'reference_number'),
    )

    reference_number_seq = Sequence('callback_request_reference_number_seq')

    uuid = Column(UUID(as_uuid=True), nullable=False, server_default=text('uuid_generate_v4()'))
    list_uuid = Column(UUID(as_uuid=True), nullable=False)
    phone_number = Column(String(40))
    mobile_phone_number = Column(String(40))
    firstname = Column(String(128))
    lastname = Column(String(128))
    company = Column(String(128))
    description = Column(Text)
    agent_id = Column(Integer)
    clotured = Column(Boolean, server_default='False')
    preferred_callback_period_uuid = Column(UUID(as_uuid=True))
    due_date = Column(Date, nullable=False, server_default=text('now()'))
    reference_number = Column(Integer,
                              reference_number_seq,
                              server_default=reference_number_seq.next_value(),
                              nullable=False)
    voice_message_ref = Column(String(128))

    callback_list = relationship(CallbackList)
    preferred_callback_period = relationship(PreferredCallbackPeriod)