#!/usr/bin/python

import sys
import imp
import os
import xml.dom.minidom
import re
import datetime
import urllib
BeautifulSoup = imp.load_source('BeautifulSoup', '/home/xbmc/.xbmc/addons/script.module.beautifulsoup/lib/BeautifulSoup.py')
common = imp.load_source('common', '/home/xbmc/.xbmc/addons/script.showgrabber/resources/lib/common.py')
search = imp.load_source('search', '/home/xbmc/.xbmc/addons/script.transmission/resources/lib/search.py')

sys.path.append('/home/xbmc/.xbmc/addons/script.transmission/resources/lib/')
import transmissionrpc
import time

SHOWGRABBER_SETTINGS_FILE_PATH="/home/xbmc/.xbmc/userdata/addon_data/script.showgrabber/settings.xml"
TRANSMISSIONXMBC_SETTINGS_FILE_PATH="/home/xbmc/.xbmc/userdata/addon_data/script.transmission/settings.xml"
SETTINGS_FILE_PATH="/home/xbmc/.xbmc/userdata/addon_data/script.postdownloader/settings.xml"

class Settings(object):
    def __init__(self,settings_file,showgrabber_file,transmissionxbmc_file):
        try:
            # From postdownloader config
            self.MAIL_ENABLED=True
            self.SENDMAIL_DEST="corvust.xbmc@gmail.com"
            self.DEFAULT_NEW_PATH="/home/xbmc/Media/New"
            self.TORRENT_DOWNLOAD_PATH="/home/xbmc/Media/.Downloads"

            # From Transmission config
            self.RPC_HOST="127.0.0.1"
            self.RPC_PORT=9091
            self.RPC_USER="xbmc"
            self.RPC_PASS="xbmcadmin"
            self.TRUSTEDONLY=True

            # From showgrabber settings
            self.TORRENT_FILE_PATH="/home/xbmc/shows.xml"
            self.SEARCHER="The Pirate Bay"

            doc = xml.dom.minidom.parse(settings_file)
            settingsNodes = doc.getElementsByTagName('setting')
            for node in settingsNodes:
                if node.attributes['id'].value == 'mail_enabled':
                    if str(node.attributes['value'].value).lower() != 'true':
                        self.MAIL_ENABLED = False
                if node.attributes['id'].value == 'mail_dest':
                    self.SENDMAIL_DEST = node.attributes['value'].value
                if node.attributes['id'].value == 'new_path':
                    self.DEFAULT_NEW_PATH = node.attributes['value'].value
                if node.attributes['id'].value == 'download_path':
                    self.TORRENT_DOWNLOAD_PATH = node.attributes['value'].value
            
            doc2 = xml.dom.minidom.parse(transmissionxbmc_file)
            settingsNodes = doc2.getElementsByTagName('setting')
            for node in settingsNodes:
                if node.attributes['id'].value == 'rpc_host':
                    self.RPC_HOST = node.attributes['value'].value
                if node.attributes['id'].value == 'rpc_port':
                    self.RPC_PORT = node.attributes['value'].value
                if node.attributes['id'].value == 'rpc_user':
                    self.RPC_USER = node.attributes['value'].value
                if node.attributes['id'].value == 'rpc_password':
                    self.RPC_PASS = node.attributes['value'].value
                if node.attributes['id'].value == 'trusted_uploaders':
                    if str(node.attributes['value'].value).lower() != 'true':
                        self.TRUSTEDONLY = False

            doc3 = xml.dom.minidom.parse(showgrabber_file)
            settingsNodes = doc3.getElementsByTagName('setting')
            for node in settingsNodes:
                if node.attributes['id'].value == 'search_provider':
                    self.SEARCHER = node.attributes['value'].value            
                if node.attributes['id'].value =='file_path':
                    self.TORRENT_FILE_PATH = node.attributes['value'].value
        except:
            pass

def sendMail(to_address,subject_text,body_text):
    sendmail_location = "/usr/sbin/sendmail" # sendmail location
    p = os.popen("%s -t" % sendmail_location, "w")
    p.write("To: %s\n" % to_address)
    p.write("Subject: %s\n" % subject_text)
    p.write("\n") # blank line separating headers from body
    p.write("%s" % body_text)
    status = p.close()
    if status != 0:
        print "Sendmail exit status", status

def mover(settings, allshows, tid = None):
    ''' The mover function is called by transmission when download is complete.
      It is responsible for extracting the proper video files from the set
      of files downloaded by the torrent, and placing them in the correct
      destination directory.
    '''
    import shutil
    import traceback
    try:
        if tid == None:
            torrent_id = os.environ.get('TR_TORRENT_ID')
        else:
            torrent_id = tid

        print 'Torrent ID: %s' % str(torrent_id)
        download_path = settings.TORRENT_DOWNLOAD_PATH

        default_video_output_path = os.path.join(settings.DEFAULT_NEW_PATH,"Video")
        default_audio_output_path = os.path.join(settings.DEFAULT_NEW_PATH,"Audio")
        
        if not os.path.exists(default_video_output_path):
            os.makedirs(default_video_output_path)
            os.makedirs(default_audio_output_path)
        video_extensions = ['mp4', 'mov', 'mkv', 'avi']
        audio_extensions = ['mp3']

        tc = transmissionrpc.Client(settings.RPC_HOST, port=settings.RPC_PORT, user=settings.RPC_USER, password=settings.RPC_PASS)
        files_dict = tc.get_files()
        torrent_list = tc.get_torrents()
        if torrent_id != None:
            id_key = int(torrent_id)
            if id_key in files_dict.keys():
                video_files = []
                audio_files = []
                for file_key in files_dict[id_key].keys():
                    file_ext = (files_dict[id_key][file_key]['name']).rsplit('.',1)[1]
                    if file_ext in video_extensions and files_dict[id_key][file_key]['name'] not in video_files:
                        video_files.append(files_dict[id_key][file_key]['name'])
                    if file_ext in audio_extensions and files_dict[id_key][file_key]['name'] not in audio_files:
                        audio_files.append(files_dict[id_key][file_key]['name'])
                for tfile in audio_files:
                    try:
                        shutil.copy(os.path.join(download_path,tfile),default_audio_output_path)
                    except:
                        pass
                for tfile in video_files:
                    print ' --> %s' % tfile
                    matches = []
                    foundShow = False
                    for show in allshows.getShows():
                        if show.enabled:
                            terms = show.filename.lower().replace('.',' ').split(' ')
                            query_str = ''
                            for term in terms:
                                if term != '':
                                    if query_str != '':
                                        query_str = query_str+'[ .]+'
                                    query_str = query_str + re.escape(term)
                            query_str = query_str + '.*'
                            match = re.search(query_str,os.path.basename(tfile).lower())
                            if match and os.path.basename(tfile).lower().find('sample') == -1:
                                print '    MATCHES'
                                foundShow = True
                                matches.append(show)
                    if not foundShow:
                        print 'No match found for torrent id %d' % id_key      
                        try:
                            shutil.copy(os.path.join(download_path,tfile),default_video_output_path)
                        except: