from werkzeug.utils import secure_filename
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import backref
from app import db
from app.utils.filesize import filesize
from config import V5Config
import os
import uuid


class Attachment(db.Model):
    __tablename__ = 'attachment'
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    # Original name of the file
    name = db.Column(db.Unicode(64))

    # The comment linked with
    comment_id = db.Column(db.Integer, db.ForeignKey('comment.id'),
        nullable=False, index=True)
    comment = db.relationship('Comment', back_populates='attachments',
        foreign_keys=comment_id)

    # The size of the file
    size = db.Column(db.Integer)

    # Storage file path
    @property
    def path(self):
        return os.path.join(V5Config.DATA_FOLDER, "attachments",
            f"{self.id}", self.name)

    @property
    def url(self):
        return f"/fichiers/{self.id}/{self.name}"


    def __init__(self, file, comment):
        self.name = secure_filename(file.filename)
        self.size = filesize(file)
        self.comment = comment

    def set_file(self, file):
        os.mkdir(os.path.dirname(self.path))
        file.save(self.path)

    def edit_file(self, file):
        file.name = secure_filename(file.filename)
        self.set_file(file)

    def delete_file(self):
        try:
            os.remove(self.path)
        except FileNotFoundError:
            pass

    def delete(self):
        self.delete_file()
        db.session.delete(self)
