import math
from datetime import datetime

import Models
from app import db
from .ProjectModel import attendance_table
from .InterestModel import interests_table


class PersonalInformationModel(Models.Base):
    __tablename__ = 'personal_information'

    user_id = db.Column(db.ForeignKey('user.id'), primary_key=True)
    user = db.relationship(
        "UserModel",
        back_populates="personal_information"
    )
    matriculation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())
    course_of_study = db.Column(db.String, nullable=True)
    description = db.Column(db.String, nullable=True)
    projects = db.relationship(
        "ProjectModel",
        secondary=attendance_table,
        order_by="desc(ProjectModel.len_attendees)",
        overlaps="attendees",
        primaryjoin="PersonalInformationModel.user_id==attend.c.user_id",
        secondaryjoin="ProjectModel.id==attend.c.project_id"
    )
    interest_list = db.relationship(
        "InterestModel",
        secondary=interests_table,
        primaryjoin="PersonalInformationModel.user_id==user_interests.c.user_id",
        secondaryjoin="InterestModel.id==user_interests.c.interest_id"
    )

    def get_interests(self, lang):
        return [i.get_name(lang) for i in self.interest_list]

    def set_interests(self, interests):
        interest_list = []
        for string in interests:
            i = Models.InterestModel.from_string(string)
            if i:
                interest_list.append(i)
        self.interest_list = interest_list

    @property
    def current_semester(self):
        delta = datetime.utcnow() - self.matriculation_date
        return math.ceil(delta.days / (365.25/2))

    def __init__(self, **kwargs):
        self.matriculation_date = datetime.utcnow()
        super().__init__(**kwargs)
