#!/usr/bin/python
# -*- coding: utf-8 -*-
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
# (C) Black_eagle 2016
#

import xbmc ,xbmcvfs, xbmcaddon
import xbmcgui
import urllib
import uuid
import sys, traceback
from resources.lib.audiodb import audiodbinfo as settings

import pickle
import datetime
if sys.version_info >= (2, 7):
    import json as _json
else:
    import simplejson as _json
from threading import Timer

rusty_gate = settings.rusty_gate
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
addonversion = addon.getAddonInfo('version')
addonpath = addon.getAddonInfo('path').decode('utf-8')
addonid = addon.getAddonInfo('id').decode('utf-8')

# variables
BaseString = addon.getSetting('musicdirectory')     # Base directory for Music albums
logostring = xbmc.translatePath('special://profile/addon_data/' + addonid +'/').decode('utf-8') # Base directory to store downloaded logos
logfile = xbmc.translatePath('special://temp/srh.log').decode('utf-8')
was_playing =""
dict1 = {} # Key = artistname+trackname, value = Album name
dict2 = {} # Key = artistname+trackname, value = Album year
dict3 = {} # Key = artistname+trackname, value = date last looked up
dict4 = {} # Key = Artist Name, Value = URL to artist thumb
dict5 = {} # Key = Artist Name, Value = URL to artist banner
dict6 = {} # Key = artist Name, value = MBID
time_diff = datetime.timedelta(days = 7) # date to next check
todays_date = datetime.datetime.combine(datetime.date.today(),datetime.datetime.min.time())
BaseString = xbmc.validatePath(BaseString)
onlinelookup = addon.getSetting('onlinelookup')
fanart = addon.getSetting('usefanarttv')
tadb = addon.getSetting('usetadb')
st1find = addon.getSetting('st1find').strip()
st1rep = addon.getSetting('st1rep').strip()
st2find = addon.getSetting('st2find').strip()
st2rep = addon.getSetting('st2rep').strip()
st3find = addon.getSetting('st3find').strip()
st3rep = addon.getSetting('st3rep').strip()
st4find = addon.getSetting('st4find').strip()
st4rep = addon.getSetting('st4rep').strip()
st5find = addon.getSetting('st5find').strip()
st5rep = addon.getSetting('st5rep').strip()
replace1 = addon.getSetting('remove1').strip().decode('utf-8')
replace2 = addon.getSetting('remove2').strip()
replace3 = addon.getSetting('remove3').strip()
firstpass = 0
WINDOW = xbmcgui.Window(12006)
debugging = addon.getSetting('debug')
if debugging == 'true' :
    debugging = True
else:
    debugging = False

def log(txt, mylevel=xbmc.LOGDEBUG):
    """
    Logs to Kodi's standard logfile
    """
    
    #if mylevel != xbmc.LOGNOTICE:
        #now = datetime.datetime.now().strftime('%H:%M:%S.%f') 
        #message = u'%s: %s' % (now, txt + '\n')
        #message = message.encode('utf-8')
        #logit.write(message)
    
    if debugging :
        mylevel=xbmc.LOGNOTICE

    if isinstance(txt, str):
        txt = txt.decode('utf-8')
    message = u'%s : %s' % (addonname, txt)
    xbmc.log(msg=message.encode('utf-8'), level=mylevel)

def load_pickle():
    """
    Loads cache data from file in the addon_data directory of the script
    """

    log("Loading data from pickle file")
    pfile = open(logostring + 'data.pickle',"rb")
    d1 = pickle.load(pfile)
    d2 = pickle.load(pfile)
    d3 = pickle.load(pfile)
    try:
        d4 = pickle.load(pfile)
        d5 = pickle.load(pfile)
    except:
        d4 = {}
        d5 = {}
        log("Pickle data for thumb and banner art didn't exist. Creating new dictionaries")
    try:
        d6 = pickle.load(pfile)
    except:
        d6={}
        log("created new pickle data for MBID storage")
    pfile.close()
    return d1,d2,d3,d4,d5,d6

def save_pickle(d1,d2,d3,d4,d5,d6):
    """
    Saves local cache data to file in the addon_data directory of the script
    """

    log("Saving data to pickle file")
    pfile = open(logostring + 'data.pickle',"wb")
    pickle.dump(d1,pfile)
    pickle.dump(d2,pfile)
    pickle.dump(d3,pfile)
    pickle.dump(d4,pfile)

    pickle.dump(d5,pfile)
    pickle.dump(d6,pfile)
    pfile.close()

def get_year(artist,track,dict1,dict2,dict3):
    """
    Look in local cache for album and year data corresponding to current track and artist.
    Return the local data if present, unless it is older than 7 days in which case re-lookup online.
    If data not present in cache, lookup online and add to cache
    If all data present in cache, just retur taht and don't lookup anyth
ing online.
    """
    if (artist == "") and (track == ""):
        return None,None
    log("Looking up album and year data for artist %s and track %s" %(artist, track), xbmc.LOGDEBUG)
    my_size = len(dict1)
    log("Cache currently holds %d tracks" % my_size, xbmc.LOGDEBUG)
    keydata = artist.replace(" ","").lower() + track.replace(" ","").lower()
    log("keydata is %s" % keydata, xbmc.LOGDEBUG)
    if keydata in dict1:
        log("Track %s in local data cache" % track, xbmc.LOGDEBUG)
        albumname = dict1[keydata]
        log("Album Name is %s" % albumname, xbmc.LOGDEBUG)
        datechecked = dict3[keydata]
        log("Data for track '%s' on album '%s' last checked %s" % (track, albumname, str(datechecked.strftime("%d-%m-%Y"))), xbmc.LOGDEBUG)
        if (datechecked < (todays_date - time_diff)) or (xbmcvfs.exists(logostring + "refreshdata")):
            log( "Data might need refreshing", xbmc.LOGDEBUG)
            if (dict1[keydata] == '') or (dict1[keydata] == None) or (dict1[keydata] == 'None') or (dict1[keydata] == 'null') or (xbmcvfs.exists(logostring + "refreshdata")):
                log("No album data - checking TADB again", xbmc.LOGDEBUG)
                dict1[keydata], dict2[keydata] = tadb_trackdata(artist,track,dict1,dict2,dict3)
                dict3[keydata] = datetime.datetime.combine(datetime.date.today(),datetime.datetime.min.time())
                log("Data refreshed")
            elif (dict2[keydata] == None) or (dict2[keydata] == '0') or (dict2[keydata] == ''):
                log("No year data for album %s - checking TADB again" % dict1[keydata], xbmc.LOGDEBUG)
                dict1[keydata], dict2[keydata] = tadb_trackdata(artist,track,dict1,dict2,dict3)
                dict3[keydata] = datetime.datetime.combine(datetime.date.today(),datetime.datetime.min.time())
                log("Data refreshed", xbmc.LOGDEBUG)
            else:
                log( "All data present - No need to refresh", xbmc.LOGDEBUG)
            return dict1[keydata], dict2[keydata]
        else:
            log( "Using cached data", xbmc.LOGDEBUG )
            return dict1[keydata],dict2[keydata]
    else:
        log("New track - get data for %s : %s" %(artist, track), xbmc.LOGDEBUG)
        dict1[keydata], dict2[keydata] = tadb_trackdata(artist,track,dict1,dict2,dict3)

        dict3[keydata] = datetime.datetime.combine(datetime.date.today(),datetime.datetime.min.time())
        log( "New data has been cached", xbmc.LOGDEBUG)
        return dict1[keydata], dict2[keydata]

def tadb_trackdata(artist,track,dict1,dict2,dict3):
    """
    Searches theaudiodb for an album containing track.  If a album is found, attempts
    to get the year of the album.  Returns album name and year if both are found, just the album name if
    no year is found, or none if nothing is found
    """

    searchartist = artist.replace(" ","+").encode('utf-8')
    searchtrack = track.replace(" ","+").encode('utf-8')
    searchtrack = searchtrack.rstrip("+")
    url = 'http://www.theaudiodb.com/api/v1/json/%s' % rusty_gate.decode( 'base64' )
    sea