#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# Copyright 2014-2015 Luca Beltrame <lbeltrame@kde.org>
# Licensed under the terms of the terms of the GPL, version 3, or later.
# See the LICENSE file for details.

import argparse
from functools import singledispatch, wraps
from enum import Enum
import os
from pathlib import Path
import re
import stat

import transmissionrpc
from xdg import Mime


class FileType(Enum):

    music = 1
    video = 2
    application = 3
    image = 4
    unknown = 100

    @staticmethod
    def detect(filelist: dict):

        # Get the largest file
        largest = max(filelist, key=lambda x: filelist[x])

        category = Mime.get_type_by_name(largest).media

        if category == "audio":
            return FileType.music
        elif category == "video":
            return FileType.video
        elif category == "application":
            return FileType.application
        elif category == "image":
            return FileType.image
        else:
            return FileType.unknown

    def destination_dir(self) -> Path:

        if self is FileType.music:
            return Path("/home/storage/music/Anime/")
        elif self is FileType.video:
            return Path("/home/storage/video/")
        elif self is FileType.application:
            return Path("/home/storage/applications/")
        elif self is FileType.image:
            return Path("/home/storage/images/")
        else:
            return Path("/home/storage/transmission-downloads/")


def main():

    # Get the information from Transmission

    source_directory = os.environ.get("TR_TORRENT_DIR")
    source_file = os.environ.get("TR_TORRENT_NAME")
    torrent_id = os.environ.get("TR_TORRENT_ID")

    with open("/var/lib/transmission/rpcpass", "r") as handle:
        rpc_pass = handle.read().strip()

    if source_directory is None or source_file is None:
        print("Please run this script from Transmission.")
        exit(1)

    source = Path(source_directory) / source_file

    assert source.exists()

    client = transmissionrpc.Client("localhost", port=9091,
                                    user="transmission", password=rpc_pass)

    # Returns a dictionary with the torrent_id as key
    filelist = client.get_files(torrent_id)[int(torrent_id)]
    filelist = {filelist[item]["name"]: filelist[item]["size"] for item in
                filelist}

    filetype = FileType.detect(filelist)

    destination = filetype.destination_dir()

    if destination == source_directory:
        return

    dest_path = destination / source.name
    source.rename(dest_path)

    permissions = dest_path.stat().st_mode
    permissions = permissions | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH
    dest_path.chmod(permissions)

    client.stop_torrent(torrent_id)
    client.remove_torrent(torrent_id)

    print("Moved {} to {}".format(source, dest_path))


if __name__ == "__main__":
    main()