import csv
class episodes():
    
    
    def __init__(self):
        pass
        
    def update_episodes(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)
            except:
                print('Unable to import episode data for for seriesid: ' + str(seriesid))
            else:
                return(eplist)
        
    def fulllisting(self, seriesid):
        pass
    
    def seasonlist(self, seriesid, seasonnumber):
        pass
    
    def process_episodes(self, episoderesults, seriesid, rootdir):
        queryrows = []
        if episoderesults:
            resultlength = len(episoderesults)
            if resultlength > 0:
                for idx, episode in enumerate(episoderesults):
                    if episoderesults[idx]['episodesummary'] is None:
                        episoderesults[idx]['episodesummary'] = 'No summary at this time.'
                    querylist = '''INSERT INTO updates.newepdata (episodeid, seriesid, season, episodenumber, episodename, airdate, airtime, episodesummary, airstamp, runtime, eplink, mediumimage, url, originalimage) VALUES\n'''
                    filename = rootdir + '/temp/' + str(seriesid) + '_episodes.sql'
                    sqlfile = open(filename, 'w', encoding="utf-8")
                    sqlfile.write(querylist)
                    try:
                        SQL = '''( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )''' % (episoderesults[idx]['episodeid'],
                        episoderesults[idx]['seriesid'], episoderesults[idx]['season'], episoderesults[idx]['episodenumber'], episoderesults[idx]['episodename'].replace("'", "''"),
                        episoderesults[idx]['airdate'], episoderesults[idx]['airtime'], episoderesults[idx]['episodesummary'].replace("'", "''"), episoderesults[idx]['airstamp'],
                        episoderesults[idx]['runtime'], episoderesults[idx]['eplink'], episoderesults[idx]['mediumimage'], episoderesults[idx]['url'], episoderesults[idx]['originalimage'])
                            #tv.insert_data(engine, episode, metadata.tables['[updates].newepdata'])
                        queryrows.append(SQL)
                    except Exception as e:
                        lprint.logprint('info', 'Unable to process episodes for seriesid: ' + str(cseriesid))
                    else:
                        qlength = len(queryrows) - 1
                        for rowidx, queryrow in enumerate(queryrows):
                            if rowidx == qlength and idx == len(episoderesults) -1:
                                sqlfile.write(queryrow + ';\n')
                            else:
                                sqlfile.write(queryrow + ',\n')
                        sqlfile.close()
                return(filename, resultlength, querylist)

    def __del__(self):
        pass
    