import json
import xbmc
import time
import urllib2
from quasar.addon import ADDON
from quasar.config import QUASARD_HOST
from quasar.provider import closing

def library_thread():
    trakt_sync = int(ADDON.getSetting("trakt_sync"))
    if trakt_sync > 0:
        limit = trakt_sync * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # trakt_sync hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(QUASARD_HOST + "/library/movie/watchlist/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/movie/collection/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/show/watchlist/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/show/collection/add?updating=true")
                    with closing(urllib2.urlopen(QUASARD_HOST + "/library/userlists")) as response:
                        data = json.loads(response.read())
                        for userlist in data:
                            urllib2.urlopen(QUASARD_HOST + "/library/movie/list/add/%d?updating=true" % userlist['IDs']['trakt'])
                            urllib2.urlopen(QUASARD_HOST + "/library/show/list/add/%d?updating=true" % userlist['IDs']['trakt'])
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
    else:
        limit = int(ADDON.getSetting("library_update_frequency")) * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # library_update_frequency hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
