"""
Upload a file and auto-complete the input with its URL.

Usage
-----

This plugin adds a command to the chat tabs.

.. glossary::

    /upload
        **Usage:** ``/upload <filename>``

        Uploads the <filename> file to the preferred HTTP File Upload
        service (see XEP-0363) and fill the input with its URL.


"""

from typing import cast

import traceback
from os.path import expanduser
from glob import glob
from pathlib import Path

from slixmpp.plugins.xep_0363.http_upload import FileTooBig, HTTPError, UploadServiceNotFound

from poezio.plugin import BasePlugin
from poezio.core.structs import Completion
from poezio.decorators import command_args_parser
from poezio.windows.inputs import Input
from poezio import tabs


class HTTPUploadNotFound(Exception):
    def __init__(self) -> None:
        super().__init__('slixmpp XEP-0363 plugin failed to load')


class Plugin(BasePlugin):
    dependencies = {'embed'}

    def init(self) -> None:
        self.embed = self.refs['embed']

        if not self.core.xmpp['xep_0363']:
            raise HTTPUploadNotFound()
        if not self.core.xmpp['xep_0453']:
            self.api.information(
                'slixmpp XEP-0454 plugin failed to load. '
                'Will not be able to encrypt uploaded files.',
                'Warning',
            )
        for _class in (tabs.PrivateTab, tabs.StaticConversationTab, tabs.DynamicConversationTab, tabs.MucTab):
            self.api.add_tab_command(
                _class,
                'upload',
                self.command_upload,
                usage='<filename>',
                help='Upload a file and auto-complete the input with its URL.',
                short='Upload a file',
                completion=self.completion_filename)

    async def upload(self, filename: Path, encrypted: bool = False) -> str | None:
        try:
            upload_file = self.core.xmpp['xep_0363'].upload_file
            if encrypted:
                upload_file = self.core.xmpp['xep_0454'].upload_file
            url = cast(str, await upload_file(filename))
        except UploadServiceNotFound:
            self.api.information('HTTP Upload service not found.', 'Error')
            return None
        except (FileTooBig, HTTPError) as exn:
            self.api.information(str(exn), 'Error')
            return None
        except Exception:
            exception = traceback.format_exc()
            self.api.information('Failed to upload file: %s' % exception,
                                 'Error')
            return None
        return url

    async def send_upload(self, filename: Path, tab: tabs.ChatTab,
                          encrypted: bool = False) -> None:
        url = await self.upload(filename, encrypted)
        if url is not None:
            self.embed.embed_image_url(url, tab)

    @command_args_parser.quoted(1)
    def command_upload(self, args: list[str]) -> None:
        if not args:
            self.core.command.help('upload')
            return
        tab = self.api.current_tab()
        if not isinstance(tab, tabs.ChatTab):
            return
        filename_str, = args
        filename = Path(expanduser(filename_str))
        encrypted = self.core.xmpp['xep_0454'] and tab.e2e_encryption is not None
        self.core.register_task(self.send_upload(filename, tab, encrypted))

    @staticmethod
    def completion_filename(the_input: Input) -> Completion:
        txt = expanduser(the_input.get_text()[8:])
        files = glob(txt + '*')
        return Completion(the_input.auto_completion, files, quotify=False)
