# -*- coding: utf-8 -*-
"""
	Venom Add-on
"""

from datetime import datetime, timedelta # timedelta could be removed
from json import dumps as jsdumps, loads as jsloads
import re
from sys import argv
try: #Py2
	from urllib import quote_plus
except ImportError: #Py3
	from urllib.parse import quote_plus
from resources.lib.database import cache
from resources.lib.indexers import tmdb as tmdb_indexer
from resources.lib.modules import cleangenre
from resources.lib.modules import control
from resources.lib.modules import log_utils
from resources.lib.modules import playcount
from resources.lib.modules import trakt
from resources.lib.modules import views


class Seasons:
	def __init__(self, type='show'):
		self.list = []
		self.type = type
		self.lang = control.apiLanguage()['tmdb']
		self.season_special = False
		self.disable_fanarttv = control.setting('disable.fanarttv')
		# self.date_time = (datetime.utcnow() - timedelta(hours=5))
		self.date_time = datetime.utcnow()
		self.today_date = (self.date_time).strftime('%Y-%m-%d')

		self.tmdb_poster_path = 'https://image.tmdb.org/t/p/w300'

		self.trakt_user = control.setting('trakt.user').strip()
		self.traktCredentials = trakt.getTraktCredentialsInfo()
		self.traktwatchlist_link = 'https://api.trakt.tv/users/me/watchlist/seasons'
		self.traktlists_link = 'https://api.trakt.tv/users/me/lists'

		self.showunaired = control.setting('showunaired') or 'true'
		self.unairedcolor = control.getColor(control.setting('unaired.identify'))


	def get(self, tvshowtitle, year, imdb, tmdb, tvdb, art, idx=True): # may need to add a cache duration over-ride param to pass
		self.list = []
		if idx:
			# self.list = self.tmdb_list(tvshowtitle, imdb, tmdb, tvdb, art)
			self.list = cache.get(self.tmdb_list, 96, tvshowtitle, imdb, tmdb, tvdb, art)
			if self.list is None: self.list = []
			self.seasonDirectory(self.list)
			return self.list
		else:
			self.list = self.tmdb_list(tvshowtitle, imdb, tmdb, tvdb, art)
			return self.list


	def tmdb_list(self, tvshowtitle, imdb, tmdb, tvdb, art):
		if not tmdb and (imdb or tvdb):
			try:
				result = cache.get(tmdb_indexer.TVshows().IdLookup, 96, imdb, tvdb)
				tmdb = str(result.get('id')) if result else ''
			except:
				log_utils.log('tvshowtitle: (%s) missing tmdb_id' % tvshowtitle, __name__, log_utils.LOGDEBUG) # log TMDb does not have show
				return
		showSeasons = cache.get(tmdb_indexer.TVshows().get_showSeasons_meta, 96, tmdb)
		if not showSeasons: return
		if art: art = jsloads(art) # prob better off leaving this as it's own dict so seasonDirectory list builder can just pull that out and pass to .setArt()

		for item in showSeasons['seasons']: # seasons not parsed in tmdb module so ['seasons'] here is direct json response data
			try:
				if not control.setting('tv.specials') == 'true' and item['season_number'] == 0: continue
				values = {}
				values.update(showSeasons)
				values['mediatype'] = 'season'
				values['premiered'] = str(item.get('air_date', '')) if item.get('air_date') else ''
				values['year'] = showSeasons['year'] # use show year not season year.  In seasonDirecotry send InfoLabels year pulled from premiered only.
				values['unaired'] = ''
				try:
					if values['status'].lower() == 'ended': pass # season level unaired
					elif not values['premiered']:
						values['unaired'] = 'true'
						if self.showunaired != 'true': continue
						pass
					elif int(re.sub(r'[^0-9]', '', str(values['premiered']))) > int(re.sub(r'[^0-9]', '', str(self.today_date))):
						values['unaired'] = 'true'
						if self.showunaired != 'true': continue
				except:
					log_utils.error()

				values['total_episodes'] = item['episode_count']
				values['season_title'] = item['name']
				values['plot'] = item['overview'] or showSeasons['plot']
				try: values['poster'] = self.tmdb_poster_path + item['poster_path']
				except: values['poster'] = ''
				if not values['poster'] and art: values['poster'] = art['poster']
				values['season_poster'] = values['poster']
				values['season'] = str(int(item['season_number']))
				if art:
					values['fanart'] = art['fanart']
					values['icon'] = art['icon']
					values['thumb'] = art['thumb']
					values['banner'] = art['banner']
					values['clearlogo'] = art['clearlogo']
					values['clearart'] = art['clearart']
					values['landscape'] = art['landscape']
				remove_keys = ('seasons',) # pop() keys from showSeasons that are not needed anymore
				for k in remove_keys: values.pop(k, None)
				self.list.append(values)
			except:
				log_utils.error()
		return self.list


	def seasonDirectory(self, items):
		if not items: # with reuselanguageinvoker on an empty directory must be loaded, do not use sys.exit()
			control.hide()
			control.notification(title=32054, message=33049)
		sysaddon, syshandle = argv[0], int(argv[1])
		is_widget = 'plugin' not in control.infoLabel('Container.PluginName')
		settingFanart = control.setting('fanart')
		addonPoster = control.addonPoster()
		addonFanart = control.addonFanart()
		addonBanner = control.addonBanner()

		try: indicators = playcount.getSeasonIndicators(items[0]['imdb'], refresh=True)
		except: indicators = None
		unwatchedEnabled = control.setting('tvshows.unwatched.enabled') == 'true'

		if trakt.getTraktIndicatorsInfo():
			watchedMenu = control.lang(32068)
			unwatchedMenu = control.lang(32069)
		else:
			watchedMenu = control.lang(32066)
			unwatchedMenu = control.lang(32067)
		traktManagerMenu = control.lang(32070)
		queueMenu = control.lang(32065)
		showPlaylistMenu = control.lang(35517)
		clearPlaylistMenu = control.lang(35516)
		labelMenu = control.lang(32055)
		playRandom = control.lang(32535)
		addToLibrary = control.lang(32551)

		try: multi = [i['tvshowtitle'] for i in items]
		except: multi = []
		multi = len([x for y,x in enumerate(multi) if x not in multi[:y]])
		multi = True if multi > 1 else False

		for i in items:
			try:
				imdb, tmdb, tvdb, year, season = i.get('imdb', ''), i.get('tmdb', ''), i.get('tvdb', ''), i.get('year', ''), i.get('season')
				title = i.get('tvshowtitle')
				label = '%s %s' % (labelMenu, i.get('season'))
				if not self.season_special and control.setting('tv.specials') == 'true':
					self.season_special = True if int(season) == 0 else False
				try:
					if i['unaired'] == 'true': label = '[COLOR %s][I]%s[/I][/COLOR]' % (self.unairedcolor, label)
				except: pass
				systitle = quote_plus(title)
				meta = dict((k, v) for k, v in control.iteritems(i) if v is not None and v != '')
				# setting mediatype to "season" causes "Infomation" and "play trailer" to not be available in some skins
				meta.update({'code': imdb, 'imdbnumber': imdb, 'mediatype': 'tvshow', 'tag': [imdb, tmdb]}) # "tag" and "tagline" for movies only, but works in my skin mod so leave
				try: meta['plot'] = control.cleanPlot(meta['plot']) # Some plots have a link at the end remove it.
				except: pass
				try: meta.update({'genre': cleangenre.lang(meta['genre'], self.lang)})
				except: pass

				# First check thumbs, since they typically contains the seasons poster. The normal poster contains the show poster.
				poster = meta.get('thumb') or meta.get('poster3') or meta.get('poster2') or meta.get('poster') or addonPoster
				season_poster = meta.get('season_poster') or poster
				landscape = meta.get('landscape')
				fanart = ''
				if settingFanart:
					fanart = meta.get('fanart3') or meta.get('fanart2') or meta.get('fanart') or landscape or addonFanart
				thumb = season_poster
				icon = meta.get('icon') or poster
				banner = meta.get('banner3') or meta.get('banner2') or meta.get('banner') or addonBanner
				art = {}
				art.update({'poster': season_poster, 'tvshow.poster': poster, 'season.poster': season_poster, 'fanart': fanart, 'icon': icon,
									'thumb': thumb, 'banner': banner, 'clearlogo': meta.get('clearlogo'), 'clearart': meta.get('clearart'), 'landscape': landscape})
				remove_keys = ('poster2', 'poster3', 'fanart2', 'fanart3', 'banner2', 'banner3')
				for k in remove_keys: meta.pop(k, None)
				meta.update({'poster': poster, 'fanart': fanart, 'banner': banner, 'thumb': thumb, 'icon': icon})

####-Context Menu and Overlays-####
				cm = []
				if self.traktCredentials:
					cm.append((traktManagerMenu, 'RunPlugin(%s?action=tools_traktManager&name=%s&imdb=%s&tvdb=%s&season=%s)' % (sysaddon, systitle, imdb, tvdb, season)))
				try:
					overlay = int(playcount.getSeasonOverlay(indicators, imdb, tvdb, season))
					watched = (overlay == 5)
					if watched:
						meta.update({'playcount': 1, 'overlay': 5})
						cm.append((unwatchedMenu, 'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&season=%s&query=4)' % (sysaddon, systitle, imdb, tvdb, season)))
					else: 
						meta.update({'playcount': 0, 'overlay': 4})
						cm.append((watchedMenu, 'RunPlugin(%s?action=playcount_TVShow&name=%s&imdb=%s&tvdb=%s&season=%s&query=5)' % (sysaddon, systitle, imdb, tvdb, season)))
				except: pass
				cm.append((playRandom, 'RunPlugin(%s?action=random&rtype=episode&tvshowtitle=%s&year=%s&imdb=%s&tvdb=%s&season=%s)' % (sysaddon, systitle, year, imdb, tvdb, season)))
				cm.append((queueMenu, 'RunPlugin(%s?action=playlist_QueueItem&name=%s)' % (sysaddon, systitle)))
				cm.append((showPlaylistMenu, 'RunPlugin(%s?action=playlist_Show)' % sysaddon))
				cm.append((clearPlaylistMenu, 'RunPlugin(%s?action=playlist_Clear)' % sysaddon))
				cm.append((addToLibrary, 'RunPlugin(%s?action=library_tvshowToLibrary&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s)' % (sysaddon, systitle, year, imdb, tmdb, tvdb)))
				cm.append(('[COLOR red]Venom Settings[/COLOR]', 'RunPlugin(%s?action=tools_openSettings)' % sysaddon))
####################################

				sysmeta = quote_plus(jsdumps(meta))
				url = '%s?action=episodes&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&meta=%s&season=%s' % (sysaddon, systitle, year, imdb, tmdb, tvdb, sysmeta, season)

				item = control.item(label=label, offscreen=True)
				if 'castandart' in i: item.setCast(i['castandart'])
				item.setArt(art)
				if unwatchedEnabled:
					try:
						count = playcount.getSeasonCount(imdb, season, self.season_special)
						if count: item.setProperties({'WatchedEpisodes': str(count['watched']), 'UnWatchedEpisodes': str(count['unwatched'])})
					except: pass
				item.setProperties({'TotalSeasons': str(meta.get('total_seasons', '')), 'TotalEpisodes': str(meta.get('total_episodes', ''))})
				item.setProperty('IsPlayable', 'false')
				if is_widget: item.setProperty('isVenom_widget', 'true')
				try: # Year is the shows year, not the seasons year. Extract year from premier date for InfoLabels to have "season_year".
					season_year = re.findall(r'(\d{4})', i.get('premiered', ''))[0]
					meta.update({'year': season_year})
				except: pass
				item.setUniqueIDs({'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb})
				item.setInfo(type='video', infoLabels=control.metadataClean(meta))
				item.addContextMenuItems(cm)
				item.addStreamInfo('video', {'codec': 'h264'})
				control.addItem(handle=syshandle, url=url, listitem=item, isFolder=True)
			except:
				log_utils.error()

		try: control.property(syshandle, 'showplot', items[0]['plot'])
		except: pass

		control.content(syshandle, 'seasons')
		control.directory(syshandle, cacheToDisc=True)
		views.setView('seasons', {'skin.estuary': 55, 'skin.confluence': 500})