
class show():
    
    def __init__(self):
        pass
    
    def process(self, metadata, showload, seriesid):
        dataresult = []
        tableresult = []
        if showload == None:
            pass
        else:
            networkid = None
            try:
                network = {}
                for key, value in showload['network'].items():
                    if key == 'country':
                        for key, value in showload['network']['country'].items():
                            if key == 'name':
                                newkey = 'country'
                                network[newkey] = showload['network']['country'][key]
                            else:
                                newkey = 'country' + key
                                network[newkey] = showload['network']['country'][key]
                    else:
                        newkey = 'network' + key
                        network[newkey] = showload['network'][key]
            except:
                #print('Failed to insert network information.')
                showload['networkid'] = 0
            else:    
                showload.pop('network')
                showload['networkid'] = network['networkid']
                dataresult.append(network)
                tableresult.append(metadata.tables['[updates].tvnetworknewvals'])
                #insertresult = insert_data(network, tables[4])
            try:
                webchannel = {}
                for key, value in showload['webChannel'].items():
                    if key == 'country':
                            if showload['webChannel'][key] is None:
                                pass
                            else:
                                for key, value in showload['webChannel']['country'].items():
                                    newkey = 'webChannelcountry'+ key
                                    webchannel[newkey] = value 
                    else:
                        webchannel[key] = value
                if key == 'name':
                    newkey = 'webChannel' + key
                    webhchannel[newkey] = value 
                if key == 'timezone':
                    newkey = 'webChannelcountry'+ key
                    webchannel[newkey] = value
            except:
                #print('Failed to insert webchannel information.')
                showload['webchannelid'] = '0'
            else:
                showload.pop('webChannel')
                showload['webchannelid'] = webchannel['id']
                webchannel['webchannelname'] = webchannel['name']
                webchannel['networkid'] = webchannel['id']
                try:
                    dataresult.append(webchannel)
                    tableresult.append(metadata.tables['[updates].tvwebchannelnewvals'])
                    #insertresult = insert_data(webchannel, tables[5])
                except sqlalchemy.exc.IntegrityError as e:
                    pass
                except Exception as e:
                    print('Failed to insert webchannel information.')
            try:
                showload['seriesid'] = showload['id']
            except:
                pass
            
            #print('TV Show: ' + showload['seriesname'])
            
            try:
                if showload['image']:
                    for key, value in showload['image'].items():
                        newkey = key + 'image' 
                        showload[newkey] = value
                    showload.pop('image')
                else:
                    showload.pop('image')
            except:
                pass
            
            try:
                if showload['externals']:
                    for key, value in showload['externals'].items():
                        showload[key] = value
                    showload.pop('externals')
                else:
                    showload.pop('externals')
            except KeyError as e:
                pass
            
            try:
                if showload['rating']:
                    for key, value in showload['rating'].items():
                        showload['rating'] = value
                
                if showload['schedule']:
                    showload['time'] = showload['schedule']['time']
                    showload['days'] = ", ".join(showload['schedule']['days'])
                    showload.pop('schedule')
            except KeyError as e:
                pass
                   
            try:
                for key, value in showload['_links']['self'].items():
                    showload[key] = value    
                showload.pop('_links')
            except KeyError as e:
                pass
            else:
                showload.pop('id')
            
            showload['genres'] = ", ".join(showload['genres'])
            
            # Finish transforming to match table columns
            showload['seriesname'] = showload.pop('name')
            showload['tvrageid'] = showload.pop('tvrage')
            showload['tvdbid'] = showload.pop('thetvdb')
            showload['imdbid'] = showload.pop('imdb')
            showload['serieslanguage'] = showload.pop('language')
            showload['seriesstatus'] = showload.pop('status')
            showload['airdays'] = showload.pop('days')
            showload['airtime'] = showload.pop('time')
            showload['showtype'] = showload.pop('type')
            showload['overview'] = showload.pop('summary')
            showload['showurl'] = showload.pop('url')
            showload['apilink'] = showload.pop('href')
            showload['officialsite'] = showload.pop('officialSite')
            
            results = []
            results.append([dataresult, tableresult, showload])
            #results.append(tableresult)
            #results.append(showload)
            return (results)

        
    def __del__(self):
        pass

class cast():
    def __init__(self):
        pass
        
    def process(self, cdata, seriesid):
        datalist = {}
        datalist['actors'] = []
        datalist['characters'] = []
        try:
            castload = json.loads(cdata)
            for idx, castdata in enumerate(castload):
                actordata = {}
                characterdata = {}
                tcharacterdata = castload[idx]['character']
                tactordata = castload[idx]['person']
                try:
                    for key, value in tactordata.items():    
                        if tactordata[key] is None:
                            pass
                        else:
                            if key == 'image':
                                for key, value in tactordata['image'].items():
                                    newkey = key + 'image' 
                                    actordata[newkey] = tactordata['image'][key]
                            elif key == '_links':
                                for key, value in tactordata['_links']['self'].items():
                                    actordata['apilink'] = tactordata['_links']['self'][key]    
                            elif key == 'country':
                                for key, value in tactordata['country'].items():
                                    newkey = 'country' + key
                                    actordata[newkey] = tactordata['country'][key]    
                            else:
                                actordata[key] = tactordata[key]
                            actordata['actorid'] = tactordata['id']
                            actordata['actorname'] = tactordata['name']
                except:
                    print('Unable to process actor information.')
                else:
                    actordata.pop('id')
                
                try:
                    if tcharacterdata:
                        for key, value in tcharacterdata.items():    
                            if key is None:
                                pass
                            else:
                                if tcharacterdata['image']:
                                    characterdata['mediumimage'] = tcharacterdata['image']['medium']
                                    characterdata['originalimage'] = tcharacterdata['image']['original']
                                characterdata['apilink'] = tcharacterdata['_links']['self']['href']    
                                characterdata['tvmazeilink'] = tcharacterdata['url']
                                characterdata['characterid'] = tcharacterdata['id']
                                characterdata['charactername'] = tcharacterdata['name']    
                                characterdata['seriesid'] = seriesid
                                characterdata['actorid'] = actordata['actorid']
                except Exception as e:
                    print('Unable to process character information. -> ' + str(e))
                    
                datalist['characters'].append(characterdata)
                datalist['actors'].append(actordata)
                linkdata = {}
                linkdata['actorid'] = actordata['actorid']
                linkdata['characterid'] = characterdata['characterid']
                #return(datalist)
        except Exception as e:
            #print('Line 389: ' + str(e))
            pass
        else:
            return(datalist)
    def __del__(self):
        pass

class Episode():
    
    def __init__(self):
        pass
        
    def process(self, epload, seriesid):
        if epload:
            eplist = []
            try:
                for epdata in epload:
                    epdata['seriesid'] = seriesid
                    if epdata['image']:
                        for key, value in epdata['image'].items():
                            newkey = key + 'image' 
                            epdata[newkey] = value
                        epdata.pop('image')
                    else:
                        epdata['mediumimage'] = 'None'
                        epdata['originalimage'] = 'None'
                        epdata.pop('image')
                    
                    for key, value in epdata['_links']['self'].items():
                        epdata['eplink'] = value    
                    epdata.pop('_links')
                    
                    epdata['episodeid'] = epdata.pop('id')
                    epdata['episodename'] = epdata.pop('name')
                    epdata['episodesummary'] = epdata.pop('summary')
                    epdata['episodenumber'] = epdata.pop('number')
                    eplist.append(epdata)
                return eplist
            except:
                print('Unable to import episode data for for seriesid: ' + str(seriesid))
        else:
            return None

    def __del__(self):
        pass
