"""Provides mail-related classes."""

from sqlalchemy import Column, Integer, ForeignKey, String, DateTime, func, \
     Boolean
from sqlalchemy.orm import relationship
from attrs_sqlalchemy import attrs_sqlalchemy
from .base import Base, OwnerMixin


@attrs_sqlalchemy
class MailMessage(Base, OwnerMixin):
    """An out of character mail message."""
    __tablename__ = 'mail_messages'
    subject = Column(String(50), nullable=True)
    sent = Column(DateTime(timezone=True), nullable=False, default=func.now())
    body = Column(String(10000), nullable=False)
    read = Column(Boolean, nullable=False, default=False)
    to_id = Column(
        Integer,
        ForeignKey('spacial_objects.id'),
        nullable=False
    )
    to = relationship(
        'SpacialObject',
        backref='received_mail',
        foreign_keys=[to_id]
    )
    parent_id = Column(
        Integer,
        ForeignKey(__tablename__ + '.id'),
        nullable=True
    )
    parent = relationship(
        'MailMessage',
        backref='replies',
        remote_side='MailMessage.id'
    )

    def __str__(self):
        return '{subject} (#{0.id})'.format(self, subject=self.get_subject())

    def get_subject(self):
        """Get a sensible subject."""
        if self.subject:
            return self.subject
        else:
            subject = 'No Subject'
            if self.parent:
                return 'RE: %s' % (self.parent.subject or subject)
            return subject

    def as_string(self):
        """Return this message as a string."""
        s = 'From: %s\n' % self.owner.title()
        s += 'To: %s\n' % self.to.title()
        s += 'Sent: %s\n' % self.sent.ctime()
        s += 'ID: %d\n' % self.id
        s += 'Subject: %s\n\n' % self.get_subject()
        s += self.body
        return s
