import datetime
import uuid

from pynamodb.attributes import NumberAttribute, UnicodeAttribute
from pynamodb.models import Model as DynamoDBTableModel

from src.system_var import environment


class UserSession(DynamoDBTableModel):
    class Meta:
        table_name = environment.SESSION_TABLE_NAME
        region = environment.AWS_REGION
    session_key = UnicodeAttribute(hash_key=True)
    user_id = UnicodeAttribute()
    id_token = UnicodeAttribute()
    doc_flg = UnicodeAttribute(null=True)
    inst_flg = UnicodeAttribute(null=True)
    bio_flg = UnicodeAttribute(null=True)
    master_mainte_flg = UnicodeAttribute(null=True)
    user_flg = UnicodeAttribute(null=True)
    refresh_token = UnicodeAttribute()
    csrf_token = UnicodeAttribute()
    last_access_time = NumberAttribute()
    record_expiration_time = NumberAttribute()

    @classmethod
    def new_last_access_time(cls):
        return datetime.datetime.now().timestamp()

    @classmethod
    def new_record_expiration_time(cls, expire=environment.SESSION_EXPIRE_MINUTE):
        last_access_time = datetime.datetime.fromtimestamp(cls.new_last_access_time())
        return (last_access_time + datetime.timedelta(minutes=expire)).timestamp()

    @classmethod
    def new(
        cls, user_id, id_token, refresh_token, csrf_token, doc_flg, inst_flg, bio_flg, master_mainte_flg, user_flg
    ):
        return cls(
            session_key=str(uuid.uuid4()),
            user_id=user_id,
            id_token=id_token,
            refresh_token=refresh_token,
            csrf_token=csrf_token,
            doc_flg=doc_flg,
            inst_flg=inst_flg,
            bio_flg=bio_flg,
            master_mainte_flg=master_mainte_flg,
            user_flg=user_flg,
            last_access_time=cls.new_last_access_time(),
            record_expiration_time=cls.new_record_expiration_time()
        )
