import mimetypes

from snek.system.service import BaseService


class ChannelAttachmentService(BaseService):
    mapper_name = "channel_attachment"

    async def create_file(self, channel_uid, user_uid, name):
        attachment = await self.new()
        attachment["channel_uid"] = channel_uid
        attachment["user_uid"] = user_uid
        attachment["name"] = name
        attachment["mime_type"] = mimetypes.guess_type(name)[0]
        attachment["resource_type"] = "file"
        real_file_name = f"{attachment['uid']}-{name}"
        attachment["relative_url"] = f"{attachment['uid']}-{name}"
        attachment_folder = await self.services.channel.get_attachment_folder(
            channel_uid
        )
        attachment_path = attachment_folder.joinpath(real_file_name)
        attachment["path"] = str(attachment_path)
        if await self.save(attachment):
            return attachment
        raise Exception(f"Failed to create channel attachment: {attachment.errors}.")
