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


"""

Auteur :      thuban <thuban@yeuxdelibad.net>

Description : Download subtitles thanks to http://thesubdb.com api

"""

import logging
import os
import sys

from .utils import progname, progversion, progurl, get_hash
from .webutils import do_req_get

logger = logging.getLogger(__name__)


class Subtitle:
    """Documentation of the API is here: http://thesubdb.com/api/"""

    API_URL = "http://api.thesubdb.com"
    USER_AGENT = "SubDB/1.0 ({}/{}; {})".format(progname, progversion, progurl)

    def __init__(self):
        pass

    @classmethod
    def search(cls, h):
        keys = {'action': "search", 'hash': h}
        myheader = {'user-agent': cls.USER_AGENT}
        r = do_req_get(cls.API_URL, "text", keys=keys, headers=myheader)

        if r:
            return r.split(',')
        else:
            logger.info("Subtitle not found")
            return False

    @classmethod
    def download(cls, hash, language, output):
        """
        Download subtitle from an hash and save it to a file

        Args:
            hash : Hash of the subtitle
            language : Language of the subtitle
            output : File to save the subtitle

        Return:
            Return True if the subtitle was found and saved else return False
        """
        keys = {'action': "download", 'hash': hash, 'language': language}
        myheader = {'user-agent': cls.USER_AGENT}
        r = do_req_get(cls.API_URL, "text", keys=keys, headers=myheader)

        if r:
            with open(output, 'w') as output:
                output.write(r)
            return True
        else:
            return False


if __name__ == '__main__':
    f = sys.argv[1]
    hash_ = get_hash(f)
    print(hash_)
    avail = Subtitle.search(hash_)
    avail = avail.split(',')
    print(avail)
    for l in avail:
        basename = os.path.splitext(f)[0]
        Subtitle.download(hash_, l, basename + '.srt')

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
