def scanFighter(fighter):

    # print status to log
    log('## Retrieving fighter details from sherdog.com: %s' % fighter)
    
    # retrieve fighter details from sherdog.com
    fighterDetails = getFighterDetails(int(fighter))
    
    # print fighter details to log
    log('Fighter ID:       %s' % fighterDetails['ID'])
    log('Fighter Name:     %s' % fighterDetails['name'].replace('\'', ''))
    log('Fighter Nickname: %s' % fighterDetails['nickName'].replace('\'', ''))
    log('Fighter Assoc.:   %s' % fighterDetails['association'].replace('\'', ''))
    log('Fighter Height:   %s' % fighterDetails['height'].replace('\'', ''))
    log('fighter Weight:   %s' % fighterDetails['weight'].replace('\'', ''))
    log('Fighter D.O.B.:   %s' % fighterDetails['birthDate'])
    log('Fighter City:     %s' % fighterDetails['city'].replace('\'', ''))
    log('Fighter Country:  %s' % fighterDetails['country'].replace('\'', ''))
    log('Fighter Image:    %s' % fighterDetails['thumbUrl'])
    
    # construct tuple of arguments for use in constructing sql query
    fighterTuple = (fighterDetails['ID'], 
                    fighterDetails['name'].replace('\'', ''),
                    fighterDetails['nickName'].replace('\'', ''),
                    fighterDetails['association'].replace('\'', ''),
                    fighterDetails['height'].replace('\'', ''),
                    fighterDetails['weight'].replace('\'', ''),
                    fighterDetails['birthDate'],
                    fighterDetails['city'].replace('\'', ''),
                    fighterDetails['country'].replace('\'', ''),
                    fighterDetails['thumbUrl'])
    
    # perform sql query
    setData("INSERT INTO fighters VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % fighterTuple)
def scanEvent(eventID):

    ## print status to log
    log('Retrieving event details from sherdog.com: %s' % eventID)
    
    ## scrape evnt details from sherdog
    event = getEventDetails(int(eventID))
    
    ## print event details to log
    log('Event ID:       %s' % event['ID'])
    log('Event Title:    %s' % event['title'].replace('\'', ''))
    log('Event Promoter: %s' % event['promotion'].replace('\'', ''))
    log('Event Date:     %s' % event['date'])
    log('Event Venue:    %s' % event['venue'].replace('\'', ''))
    log('Event City:     %s' % event['city'].replace('\'', ''))
    
    ## construct tuple of arguments to pass to sql statement
    eventTuple = (  event['ID'],
                    event['title'].replace('\'', ''),
                    event['promotion'].replace('\'', ''),
                    event['date'], event['venue'].replace('\'', ''),
                    event['city'].replace('\'', ''),
                    event['fights'].replace('\'', ''))
    
    ## execute sql to add data to dataset
    if setData("INSERT INTO events VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s')" % eventTuple, deferCommit = True):
        
        ## loop over all fighters on event
        for fighter in event['fighters']:
            
            ## insert fight record into fights table
            if not setData("INSERT INTO fights VALUES('%s', '%s')" % (event['ID'], fighter), deferCommit = True):
                
                ## break if unable to add to database
                break
        
        ## print success to log
        log('Retrieved event details from sherdog.com: %s' % eventID)
        
        # commit event to database
        setData()
    
    else:
    
        ## log error to database
        log('Error Retrieving event details from sherdog.com: %s' % eventID, xbmc.LOGERROR)
def updateLibrary():

    ## print message to log
    log('Updating Library')
    
    ## possible filenames for event ID files (subject to change)
    idFiles = ['event.nfo', 'sherdogEventID.nfo', 'sherdogEventID']
   
    ## check if user has requested full rescan
    if __addon__.getSetting("forceFullRescan") == 'true':
        
        ## drop all tables if user has selected full rescan
        setData("DROP TABLE IF EXISTS events")
        setData("DROP TABLE IF EXISTS fighters")
        setData("DROP TABLE IF EXISTS fights")
        
        ## set setting to false after dropping tables
        __addon__.setSetting(id="forceFullRescan", value='false')
        
    ## create metadata tables in database if they don't exist
    setData("CREATE TABLE IF NOT EXISTS fights(eventID TEXT, fighterID TEXT, PRIMARY KEY (eventID, fighterID))")
    setData("CREATE TABLE IF NOT EXISTS events(eventID TEXT PRIMARY KEY, title TEXT, promotion TEXT, date TEXT, venue TEXT, city TEXT, fightList TEXT)")
    setData("CREATE TABLE IF NOT EXISTS fighters(fighterID TEXT PRIMARY KEY, name TEXT, nickName TEXT, association TEXT, height TEXT, weight TEXT, birthDate TEXT, city TEXT, country TEXT, thumbURL TEXT)")
    
    ## drop and recreate library (IDs, paths) table
    setData("DROP TABLE IF EXISTS library")
    setData("CREATE TABLE library(ID TEXT, path TEXT)")
    
    ## show progress dialog
    dialogProgress.create(__addonname__, __localize__(32026))
    
    ## set count of found directories to 0
    dirCount = 0
    
    ## find all directories in configured library path
    dirList = getDirList(__addon__.getSetting("libraryPath"))
    
    ## loop over all directories in configured library path
    for directory in dirList:
        
        ## check if user has pressed cancel
        if not dialogProgress.iscanceled():
            
            ## increment directory count
            dirCount += 1
            
            ## update progress dialog
            dialogProgress.update(int((dirCount / float(len(dirList))) * 100), __localize__(32031), directory, '')
            
            ## loop over possible filenames for event ID files (soon to be removed)
            for idFile in idFiles:
                
                ## construct path to ID file
                pathIdFile = os.path.join(directory, idFile)
                
                ## check if ID file exists
                if xbmcvfs.exists(pathIdFile):

                    try:
                        
                        ## attempt to open ID file and read ID
                        eventID = open(pathIdFile).read()
                    
                    except IOError:
                        
                        ## copy ID file locally if unable to open
                        tmpID = os.path.join(__addondir__, 'tmpID')
                        
                        if xbmcvfs.copy(pathIdFile, tmpID):
                            
                            ## attempt to open ID file and read ID
                            eventID = open(tmpID).read()
                            
                            ## delete temporary file
                            xbmcvfs.delete(tmpID)
                            
                        else:
                            
                            ## set ID to empty string if unable to read ID file
                            eventID = ''
                    
                    ## strip any newlines or whitespace from ID
                    eventID = eventID.strip()
                    
                    ## check that ID is not blank
                    if eventID == '':
                        
                        ## print error to log
                        log('Event ID file found but was empty : %s' % directory, xbmc.LOGERROR)
                        
                    else:
                        
                        ## print details of found event to log
                        log('Event ID/path found (%s): %s' % (eventID, directory))
                        
                        ## insert event ID and path into library table
                        setData('INSERT INTO library VALUES("%s", "%s")' % (eventID, directory))
                        
                        ## stop checking for ID file if ID found
                        break
    
    ## set event count to 1
    eventCount = 1
    
    ## get list of unscanned event IDs
    unscannedEvents = getMissingEvents()
    
    ## loop over list of unscanned events
    for eventID in unscannedEvents:

        ## check if user has pressed cancel
        if not dialogProgress.iscanceled():

            ## update progress dialog
            dialogPercentage = int((eventCount / float(len(unscannedEvents))) * 100)
            line1 = __localize__(32027)
            line2 = '%s: %s' % (__localize__(32028), eventID)
            line3 = ''
            dialogProgress.update(dialogPercentage, line1, line2, line3)
            
            ## scrape event and add to databse
            scanEvent(eventID)
            
            ## increment event count
            eventCount += 1
    
    ## set fighter count to 1
    fighterCount = 1

    ## get list of unscanned event IDs
    unscannedFighters = getMissingFighters()

    ## loop over list of unscanned fighter IDs
    for fighter in unscannedFighters:
        
        ## check if user has pressed cancel
        if not dialogProgress.iscanceled():
            
            # update onscreen progress dialog
            dialogPercentage = int((fighterCount / float(len(unscannedFighters))) * 100)
            line1 = __localize__(32029)
            line2 = '%s: %s' % (__localize__(32030), fighter)
            line3 = ''
            dialogProgress.update(dialogPercentage, line1, line2, line3)
    
            ## scrape event and add to databse
            scanFighter(fighter)
            
            ## increment event count
            fighterCount += 1
    
    ## close progress dialog
    dialogProgress.close()