#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk

from twisted.internet import gtk2reactor
gtk2reactor.install()

from downpour.remote import commands
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from optparse import OptionParser
import logging
import os

class DownpourTorrentHandler:

    config = {
            'host': '192.168.1.4',
            'port': 6226,
            'username': 'mediacenter',
            'password': 'media'
            }
    file = None
    options = None

    def add_torrent(self, widget, data=None):

        # Listen for manager connections)
        c = ClientCreator(reactor, amp.AMP)
        if self.config['host'].startswith('/'):
            c.connectUNIX(self.config['host']).addCallback(self.connectSuccess
                ).addErrback(self.fatalError)
        else:
            c.connectTCP(self.config['host'], self.config['port']
                ).addCallback(self.connectSuccess).addErrback(self.fatalError)
        reactor.run()

    # Connection handlers
    def connectSuccess(self, client):
        client.callRemote(commands.Auth,
                username=self.config['username'],
                password=self.config['password']
            ).addCallback(self.loginComplete, client
            ).addErrback(self.fatalError);

    def loginComplete(self, result, client):

        if not result['result']:
            raise Exception('Login failed')

        params = {}
        if os.access(self.file, os.R_OK):
            f = open(self.file)
            torrentdata = f.read()
            f.close()
            client.callRemote(commands.TorrentAddFile, data=torrentdata).addCallback(self.commandSuccess, client).addErrback(self.fatalError)
        else:
            raise Exception('Unable to read file %s' % self.file);

    def commandSuccess(self, result, p):
        reactor.stop()

    def fatalError(self, failure):
        print failure.getErrorMessage()
        reactor.stop()
        self.destroy(None)

    def delete_event(self, widget, event, data=None):
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self, file, options):

        self.file = file
        self.options = options

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)

        self.button = gtk.Button("Add to Downpour")
        self.button.connect("clicked", self.add_torrent, None)
        self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

        self.window.add(self.button)
        self.button.show()
        self.window.show()

    def main(self):

        gtk.main()

if __name__ == "__main__":

    parser = OptionParser(add_help_option=False)
    parser.add_option("-t", "--type", dest="type", help="The type of media this torrent contains (music, tv, movie)")
    parser.add_option("--help", action="help", help="Display this help message")
    (options, args) = parser.parse_args()

    if len(args) == 0:
        raise Exception('No file specified')

    file = args.pop(0)

    handler = DownpourTorrentHandler(file, options)
    handler.main()
