#!/usr/bin/python
# -*- coding: utf-8 -*-

'''*
	Copyright (C) 2015 apep

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*'''

import sys
import os
import re
import xbmc
import xbmcgui
import xbmcaddon
from dudehere.routines import *
from dudehere.routines import plugin
from dudehere.routines.plugin import ContextMenu, ProgressBar, TextBox
from dudehere.routines.validators import *
from resources.lib.constants import *
from resources.lib.i18n_strings import STRINGS as STRINGS_MAP
from dudehere.routines.i18nlib import i18n, LANGUAGE_PATH

STRINGS = STRINGS_MAP()

def validate_advanced():
	return plugin.get_setting('advanced_mode_1') == 'true'

plugin.replace_context_menu_by_default = True
plugin.default_context_menu_items =[
	('Walter Sobchak', {'mode': 'manage_walter'}, True, validate_walter),
	(30034, {'mode': 'manage_transmogrifier'}, True, validate_transmogrifier),
	(30033, {"mode": "set_language"}, True), 
	(30032, {"mode": "ugottoc_settings", "addon_id": ADDON_ID}, True)
]


if DB_TYPE == 'mysql':
	from dudehere.routines.database import MySQLDatabase as DatabaseAPI
else:
	from dudehere.routines.database import SQLiteDatabase as DatabaseAPI
	
if not vfs.exists(DATA_PATH): vfs.mkdir(DATA_PATH)

class MyDatabaseAPI(DatabaseAPI):
	def _initialize(self):
		schema_file = vfs.join(ROOT_PATH, 'resources/database/schema.%s.sql' % self.db_type)
		if self.run_script(schema_file, commit=False):
			self.execute('DELETE FROM version_alluc WHERE 1')
			self.execute('INSERT INTO version_alluc(db_version) VALUES(?)', [self.db_version])
			self.commit()
		
	def do_init(self):
		do_init = True
		try:
			test = self.query("SELECT 1 FROM version_alluc WHERE db_version >= ?", [self.db_version], silent=True)
			if test:
				do_init = False
		except Exception, e:
			plugin.log(e)
			do_init = True
		return do_init
DB_VERSION = 5
if DB_TYPE == 'mysql':
	DB=MyDatabaseAPI(DB_ADDRESS, DB_NAME, DB_USER, DB_PASS, DB_PORT, version=DB_VERSION, connect=True)
else:
	DB=MyDatabaseAPI(DB_FILE, version=DB_VERSION, connect=False)


def update_run():
	if plugin.check_version(plugin.get_setting('version'), '1.2.7'):
		from dudehere.routines.window import Window

		class UpdateWindow(Window):
			def __init__(self, title, show_frame=True):
				super(self.__class__,self).__init__(title,width=750, height=650, columns=3, rows=10)
			
			def proceed(self):
				from dudehere.routines.trakt import TraktAPI
				plugin.set_setting('version', VERSION)
				self.close()
			
			def set_info_controls(self):
				self.main_bg = xbmcgui.ControlImage(1, 1, 1280, 720, vfs.join(ROOT_PATH, 'fanart.jpg'))
				self.addControl(self.main_bg)

				label = self.create_label("UGOTTOC: %s" % VERSION, alignment=2, textColor='0xFFFFA500', font='font13_title')
				self.add_label(label, 0, 0, pad_x=15, pad_y=10, columnspan=3)
				
				
				label = self.create_label(i18n(33055), alignment=2)
				self.add_label(label, 1, 0, pad_x=15, pad_y=10, columnspan=3, rowspan=4)
				
				
				self.create_button("proceed", i18n(33056))
				self.add_object("proceed", 8, 1)
				self.set_focus("proceed")
				self.set_object_event('action', "proceed", self.proceed)
		
		U = UpdateWindow('TRW Update %s' % VERSION)
		U.show()
		del U
plugin.update_run = update_run

def first_run(upgrade=False):

	from dudehere.routines.window import Window
	from dudehere.routines.manager import Manager

	class FirstPage(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title)
			self.overide_actions = {"next_button": self.erase_and_next}
			self.overide_strings = {"next_button": i18n(33011)}
			
		def erase_and_next(self):
			plugin.initialize_settings(upgrade)
			WM.next_page()
			
		def set_info_controls(self):
			def cancel():
				self.close()
				plugin.exit()
			content = i18n(33000)
			self.add_label(self.create_label(content), 0, 0, columnspan=4, rowspan=5, pad_x=15, pad_y=10)
			
			self.create_button("cancel", i18n(33013))
			self.add_object("cancel", 5, 0)
			self.set_object_event('action', 'cancel', cancel)
			
	class SecondPage(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title, width=800, height=450, columns=4, rows=6)
			self.overide_strings = {"next_button": i18n(33014), "previous_button": i18n(33012)}
			
		def set_info_controls(self):	
			path = vfs.join(LANGUAGE_PATH, 'disclosure.txt', True)
			content  = vfs.read_file(path)
			self.add_label(self.create_label(content), 0, 0, columnspan=4, rowspan=5, pad_x=15, pad_y=10)
			
			self.create_button("decline", i18n(33015))
			self.add_object("decline", 5, 2)
			def decline():
				self.close()
				plugin.exit()
			self.set_object_event("action", "decline", decline)
			
	class ThirdPage(Window):	
		def set_info_controls(self):
			self.overide_strings = {"next_button": i18n(33011), "previous_button": i18n(33012)}
			content = i18n(33001)
			self.add_label(self.create_label(content), 0, 0, columnspan=4, rowspan=3, pad_x=15, pad_y=10)
			
			self.create_list('usage')
			self.add_object('usage', 2,0,3,4)
			self.add_list_items('usage', [i18n(30054), i18n(30055)], 0, allow_multiple=False, allow_toggle=False)
			
	class FourthPage(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title)
			self.overide_strings = {"next_button": i18n(33011), "previous_button": i18n(33012)}
			
		def set_info_controls(self):
			from resources.lib.language import LanguageClass
			lang = LanguageClass()
			def set_lang():
				obj = self.getFocus()
				for index in xrange(self.get_object('language').size()):
					selected = self.get_object('language').getListItem(index).getLabel2()
					if selected:
						self.get_object('language').getListItem(index).setLabel(selected)
						self.get_object('language').getListItem(index).setLabel2('')
				#
				language = obj.getSelectedItem().getLabel()
				obj.getSelectedItem().setLabel('[B][COLOR %s]%s[/COLOR][/B]' % (ENABLED_COLOR, language))
				obj.getSelectedItem().setLabel2(language)
				code = lang.get_code_by_lang(language)
				if code:
					plugin.set_setting('alluc_api_language', code)
				else:
					plugin.set_setting('alluc_api_language', '')
				
			content = i18n(33002)
			self.add_label(self.create_label(content), 0, 0, columnspan=4, rowspan=3, pad_x=15, pad_y=10)
			self.create_list('language')
			self.add_object('language', 1,0,5,4)
			self.add_list_items('language', lang.get_languages(), selectable=False, call_back=set_lang)
			
			for index in xrange(self.get_object('language').size()):
				language = self.get_object('language').getListItem(index).getLabel()
				code = lang.get_code_by_lang(language)
				if code:
					icon = vfs.join(ARTWORK, 'flags/%s.png' % code)
					self.get_object('language').getListItem(index).setIconImage(icon)
				else:
					self.get_object('language').getListItem(index).setLabel('[B][COLOR %s]%s[/COLOR][/B]' % (ENABLED_COLOR, language))
					self.get_object('language').getListItem(index).setLabel2(language)

				
	class FifthPage(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title)
			self.overide_strings = {"next_button": i18n(33011), "previous_button": i18n(33012)}
			
			def next_action():
				#valid = True
				#from dudehere.routines.scrapers import ScraperPool
				#Scraper = ScraperPool(load=['alluc_api'])
				username = self.get_value('username')
				password = self.get_value('password')
				#valid = Scraper.get_scraper_by_index(0).check_authentication(username, password)
				#if not valid:
				#	plugin.dialog_ok(i18n(33006), i18n(33007))

				#if valid:
				#	self.get_object('verified').setVisible(True)
				plugin.set_setting('alluc_api_username', username)
				plugin.set_setting('alluc_api_password', password)
				WM.next_page()
			
			self.overide_actions = {"next_button": next_action}
				
		def set_info_controls(self):
					
			self.add_label(self.create_label(i18n(33003)), 0, 0, columnspan=4, rowspan=2, pad_x=15, pad_y=10)
			
			self.add_label(self.create_label(i18n(33004), alignment=1), 2, 0, pad_x=15)
			
			self.create_input('username')
			self.add_object('username', 2, 1, columnspan=2)
			self.set_value('username', plugin.get_setting('alluc_api_username'))
			
			self.add_label(self.create_label(i18n(33005), alignment=1), 3, 0, pad_x=15)
			
			self.create_input('password', isPassword=True)
			self.add_object('password', 3, 1, columnspan=2)
			self.set_value('password', plugin.get_setting('alluc_api_password'))
			
			self.create_image('verified', ARTWORK + 'checked.png', aspectRatio=2)
			self.add_object('verified', 2, 3)
			self.get_object('verified').setVisible(False)

			
	class SixthPage(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title, width=800, height=400, columns=4, rows=6)
			self.overide_strings = {"previous_button": i18n(33012)}
		
		def cancel(self):
			plugin.set_property('Abort', "true")
			self.close()
		
		def update_timeout(self, remain):
			self.timeout.setLabel(i18n(33050) % remain)
			
		def authorize(self):
			authorize_trakt()

		def set_info_controls(self):
			content = i18n(33008)
			self.add_label(self.create_label(content), 0, 0, columnspan=4, rowspan=3, pad_x=15, pad_y=10)
			
			self.url_label =  self.create_label('')
			self.placeControl(self.url_label, 3, 0, columnspan=4, pad_x=15, pad_y=10)

			self.create_button('authorize',  i18n(33017))
			self.add_object('authorize', 5, 2)	
			self.set_object_event('action', "authorize", self.authorize)
			
			self.create_button('finalize', i18n(33016))
			self.add_object('finalize', 5, 3)
			
	class ConfirmationPage(Window):	
		def set_info_controls(self):
			bg = vfs.join(ARTWORK, 'confirmation.jpg')
			self.create_image('background', bg, aspectRatio=0)
			self.add_object('background', 0, 0, rowspan=6, columnspan=3, pad_x=0, pad_y=0)
			self.add_label(self.create_label(i18n(33010), alignment=2, font="font14"), 0, 0, columnspan=3, rowspan=5, pad_x=15, pad_y=15)

	WM = Manager()
	WM.add_page(FirstPage(i18n(33021) % VERSION))
	WM.add_page(SecondPage(i18n(33022)  % VERSION))
	WM.add_page(ThirdPage(i18n(33023) % VERSION))
	WM.add_page(FourthPage(i18n(33024) % VERSION))
	WM.add_page(FifthPage(i18n(33025) % VERSION))
	WM.add_page(SixthPage(i18n(33026) % VERSION))
	WM.add_confirmation(ConfirmationPage(i18n(33027)))
	WM.build(vfs.join(ROOT_PATH, 'fanart.jpg'))
	def complete_setup():
		WM.show_confirmation()
		plugin.set_setting('setup_run', 'true')
		plugin.set_setting('version', VERSION)
		usage_mode = WM.get_value(2, 'usage')
		if usage_mode[1]:
			for i in range(1,8):
				plugin.set_setting('advanced_mode_%s' %  i, 'true')
	WM.set_object_event(5, "action", "finalize", complete_setup)
	WM.set_focus(0, 'next_button')
	WM.set_object_event(0, 'left', 'next_button', 'cancel')
	WM.set_object_event(0, 'right', 'cancel', 'next_button')
	WM.set_focus(1, 'decline')
	WM.set_object_event(1, 'left', 'next_button', 'decline')
	WM.set_object_event(1, 'left', 'decline', 'previous_button')
	WM.set_object_event(1, 'right', 'decline', 'next_button')
	WM.set_object_event(1, 'right', 'previous_button', 'decline')
	WM.set_focus(2, 'next_button')
	WM.set_object_event(2, 'left', 'next_button', 'previous_button')
	WM.set_object_event(2, 'right', 'previous_button', 'next_button')
	WM.set_object_event(2, 'up', 'next_button', 'usage')
	WM.set_object_event(2, 'up', 'previous_button', 'usage')
	WM.set_object_event(2, 'down', 'usage', 'next_button')
	WM.set_object_event(2, 'right', 'usage', 'next_button')
	WM.set_focus(3, 'next_button')
	WM.set_object_event(3, 'left', 'next_button', 'previous_button')
	WM.set_object_event(3, 'right', 'previous_button', 'next_button')
	WM.set_object_event(3, 'up', 'next_button', 'language')
	WM.set_object_event(3, 'up', 'previous_button', 'language')
	WM.set_object_event(3, 'down', 'language', 'next_button')
	WM.set_object_event(3, 'right', 'language', 'next_button')
	WM.set_focus(4, 'username')
	WM.set_object_event(4, 'left', 'next_button', 'previous_button')
	WM.set_object_event(4, 'right', 'previous_button', 'next_button')
	WM.set_object_event(4, 'up', 'next_button', 'password')
	WM.set_object_event(4, 'up', 'previous_button', 'password')
	WM.set_object_event(4, 'up', 'password', 'username')
	WM.set_object_event(4, 'down', 'username', 'password')
	WM.set_object_event(4, 'down', 'password', 'next_button')
	
	WM.set_focus(5, 'finalize')
	WM.set_object_event(5, 'left', 'finalize', 'authorize')
	WM.set_object_event(5, 'left', 'authorize', 'previous_button')
	WM.set_object_event(5, 'right', 'previous_button', 'authorize')
	WM.set_object_event(5, 'right', 'authorize', 'finalize')
	WM.show()
	plugin.set_property('Abort', "false")
plugin.first_run = first_run	


def main_menu():
	plugin.add_menu_item({'mode': 'tv_menu'}, {'title': STRINGS.map('tv_menu')}, image=ARTWORK + 'tvshows.jpg')
	plugin.add_menu_item({'mode': 'movie_menu'}, {'title': STRINGS.map('movie_menu')}, image=ARTWORK + 'movies.jpg')
	plugin.add_video_item({'mode': 'quick_search'}, {'title': STRINGS.map('quick_search')}, image=ARTWORK + 'search_quick.jpg')
	plugin.add_menu_item({'mode': 'settings_menu'}, {'title': STRINGS.map('settings_menu')}, image=ARTWORK + 'settings_ugottoc.jpg')
	plugin.add_menu_item({'mode': 'authorize_trakt'}, {'title': STRINGS.map('authorize_trakt')}, image=ARTWORK + 'trakt.jpg', visible=validate_trakt()==False)
	plugin.add_menu_item({'mode': 'show_help'}, {'title': STRINGS.map('show_help')}, image=ARTWORK + 'help.jpg')
	plugin.eod(clear_search=True)
plugin.register('main', main_menu)

def tv_menu():
	plugin.add_menu_item({'mode': 'tv_favorites'}, {'title': STRINGS.map('my_favorites')}, image=ARTWORK + "favorites.jpg", visible=validate_trakt()==False)
	plugin.add_menu_item({'mode': 'tv_calendar'}, {'title': STRINGS.map('tv_calendar')}, image=ARTWORK + 'calendar.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'next_on_trakt'}, {'title': STRINGS.map('next_on_trakt')}, image=ARTWORK + 'next_on_trakt.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'tv_watchlist'}, {'title': STRINGS.map('watchlist')}, image=ARTWORK + 'watchlist.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'tv_collection'}, {'title': STRINGS.map('collection')}, image=ARTWORK + 'collection.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'tv_custom_lists'}, {'title': STRINGS.map('custom_lists')}, image=ARTWORK + 'custom_list.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'tv_recommended'}, {'title': STRINGS.map('tv_recommended')}, image=ARTWORK + 'recommended.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'tv_popular'}, {'title': STRINGS.map('tv_popular')}, image=ARTWORK + 'popular.jpg')
	plugin.add_menu_item({'mode': 'tv_trending'}, {'title': STRINGS.map('tv_trending')}, image=ARTWORK + 'trending.jpg')
	plugin.add_menu_item({'mode': 'tv_search'}, {'title': STRINGS.map('search')}, image=ARTWORK + 'search.jpg')
	plugin.eod(clear_search=True)
plugin.register('tv_menu', tv_menu)

def movie_menu():
	plugin.add_menu_item({'mode': 'movie_favorites'}, {'title': STRINGS.map('my_favorites')}, image=ARTWORK + "favorites.jpg", visible=validate_trakt()==False)
	plugin.add_menu_item({'mode': 'movie_watchlist'}, {'title': STRINGS.map('watchlist')}, image=ARTWORK + 'watchlist.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'movie_collection'}, {'title': STRINGS.map('collection')}, image=ARTWORK + 'collection.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'movie_custom_lists'}, {'title': STRINGS.map('custom_lists')}, image=ARTWORK + 'custom_list.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'movie_recommended'}, {'title': STRINGS.map('movie_recommended')}, image=ARTWORK + 'recommended.jpg', visible=validate_trakt)
	plugin.add_menu_item({'mode': 'movie_popular'}, {'title': STRINGS.map('movie_popular')}, image=ARTWORK + 'popular.jpg')
	plugin.add_menu_item({'mode': 'movie_trending'}, {'title': STRINGS.map('movie_trending')}, image=ARTWORK + 'trending.jpg')
	plugin.add_menu_item({'mode': 'movie_search'}, {'title': STRINGS.map('search')}, image=ARTWORK + 'search.jpg')
	plugin.eod(clear_search=True)
plugin.register('movie_menu', movie_menu)
	
def settings_menu():
	plugin.add_menu_item({'mode': 'authorize_trakt'}, {'title': STRINGS.map('authorize_trakt')}, image=ARTWORK + 'trakt.jpg')
	plugin.add_menu_item({'mode': 'manage_hostlist'}, {'title': STRINGS.map('manage_hostlist')}, image=ARTWORK + 'hoster_list.jpg', visible=False)
	plugin.add_menu_item({'mode': 'advanced_mode'}, {'title': STRINGS.map('enable_basic_mode')}, image=ARTWORK + "advanced_mode.jpg", visible=validate_advanced())
	plugin.add_menu_item({'mode': 'advanced_mode'}, {'title': STRINGS.map('enable_advanced_mode')}, image=ARTWORK + "basic_mode.jpg", visible=validate_advanced() is False)
	plugin.add_menu_item({'mode': 'ugottoc_settings', 'addon_id': 'plugin.video.ugottoc'}, {'title': STRINGS.map('ugottoc_settings')}, image=ARTWORK + 'settings_ugottoc.jpg')
	plugin.add_menu_item({'mode': 'transmogrifier_settings', 'addon_id': 'service.transmogrifier'}, {'title': STRINGS.map('transmogrifier_settings')}, image=ARTWORK + 'transmogrified.jpg', visible=validate_transmogrifier)
	plugin.add_menu_item({'mode': 'urlresolver_settings', 'addon_id': 'script.module.urlresolver'}, {'title': STRINGS.map('urlresolver_settings')}, image=ARTWORK + 'urlresolver.jpg')
	plugin.add_menu_item({'mode': 'clear_cache'}, {'title': STRINGS.map('clear_cache')}, image=ARTWORK + 'clear_cache.jpg')
	plugin.add_menu_item({'mode': 'reset_ugottoc'}, {'title': STRINGS.map('reset_ugottoc')}, image=ARTWORK + 'reset.jpg')
	plugin.eod(clear_search=True)
plugin.register('settings_menu', settings_menu)
	
def transmogrified_menu():
	plugin.add_menu_item({'mode': 'tv_transmogrified'}, {'title': STRINGS.map('tv_transmogrified')}, image=ARTWORK + 'add_source_folders.jpg')
	plugin.add_menu_item({'mode': 'movie_transmogrified'}, {'title': STRINGS.map('movie_transmogrified')}, image=ARTWORK + 'subscriptions.jpg')
	plugin.add_menu_item({'mode': 'transmogrifier_queue'}, {'title': STRINGS.map('transmogrifier_queue')}, image=ARTWORK + 'hoster_list.jpg')
	plugin.eod(clear_search=True)
plugin.register('transmogrified_menu', transmogrified_menu)


def next_on_trakt():
	if not plugin.get_setting('default_trakt_list'): 
		set_default_list()
	skin_path = plugin.get_addon('script.module.dudehere.routines').getAddonInfo('path')
	from dudehere.routines.windows.next_on_trakt import OnNextWindow
	g = OnNextWindow("onnext.xml", skin_path)
	g.doModal()
	del g

plugin.register('next_on_trakt', next_on_trakt)	

def set_default_list():
	skin_path = plugin.get_addon('script.module.dudehere.routines').getAddonInfo('path')
	from dudehere.routines.windows.default_list import SetListWindow
	LI = SetListWindow("setlist.xml", skin_path)
	LI.doModal()
	del LI	
plugin.register('set_default_list', set_default_list)	

def tv_list():

	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	if plugin.mode == 		'tv_watchlist' or validate_trakt() is False:
		watchlist = []
	else:
		watchlist = trakt.get_watchlist_tvshows(simple=True)
	if plugin.mode == 		'tv_favorites':
		results = trakt.get_favorites('tvshow')
	elif plugin.mode == 		'tv_collection':
		results = trakt.get_collected_tvshows()
	elif plugin.mode == 		'tv_watchlist':
		results = trakt.get_watchlist_tvshows()
		if not results: return
		regex = re.compile("^(A )|(An )|(The )", re.IGNORECASE)
		def sort_results(title):
			title = regex.sub('', title['show']['title'], re.IGNORECASE)
			return title.lower()
		results.sort(key=lambda k: sort_results(k))
	elif plugin.mode == 	'tv_trending':
		results = trakt.get_trending_tvshows()
	elif plugin.mode == 	'tv_popular':
		results = trakt.get_popular_tvshows()
	elif plugin.mode ==		'tv_recommended':
		results = trakt.get_recommended_tvshows()
	elif plugin.mode ==		'tv_custom_list':
		results = trakt.get_custom_list(plugin.args['slug'], 'tvshows')	
		if not results: return
		regex = re.compile("^(A )|(An )|(The )", re.IGNORECASE)
		def sort_results(title):
			title = regex.sub('', title['show']['title'], re.IGNORECASE)
			return title.lower()
		results.sort(key=lambda k: sort_results(k))
	elif plugin.mode ==		'tv_search':
		query = plugin.get_property('search.query.refesh')
		if query:
			plugin.clear_property('search.query')
			plugin.clear_property('search.query.refesh')
		else:
			query = plugin.dialog_input(i18n(30056))
		if query is None: 
			plugin.clear_property("search.query")
			return
		plugin.set_property('search.query', query)
		results = trakt.search(query, 'show')
	elif plugin.mode == 	'tv_similar':
		results = trakt.get_similar_tvshows(plugin.args['imdb_id'])		
	if not results:
		return
	count = len(results)
	for record in results:
		record = trakt.process_record(record, media='tvshow')
		menu = ContextMenu()
		menu.add("Find Similar Shows", {"mode": "tv_similar", "imdb_id": record['imdb_id']})
		if plugin.mode == 	'tv_watchlist':
			menu.add(30037, {"mode": "tv_delete_from_watchlist", "imdb_id": record['imdb_id'], "name": record['title']}, script=True, visible=validate_trakt)
		else:
			if record['imdb_id'] in watchlist: 
				record['title'] = '[COLOR %s]%s[/COLOR]' % (WATCHLIST_COLOR, record['title'])
				menu.add(30037, {"mode": "tv_delete_from_watchlist", "imdb_id": record['imdb_id'], "name": record['title']}, script=True, visible=validate_trakt)
			else:
				menu.add(30038, {"mode": "tv_add_to_watchlist", "imdb_id": record['imdb_id']}, script=True, visible=validate_trakt)
				
		if plugin.mode ==	'tv_custom_list':
			menu.add(30039, {"mode": "delete_from_custom_list", "media": "tvshow", "imdb_id": record['imdb_id'], "slug": plugin.args['slug'], "name": record['title']}, script=True, visible=validate_trakt)
		else:
			menu.add(30040, {"mode": "add_to_custom_list", "media": "tvshow", "imdb_id": record['imdb_id']}, script=True, visible=validate_trakt)	
		if plugin.mode ==	'tv_favorites':
			menu.add('Delete Favorite', {"mode": "delete_from_favorites", "media": "tvshow", "title": record['title'], "trakt_id": record['trakt_id']}, script=True, visible=validate_trakt()==False)
		else:
			menu.add('Save as Favorite', {"mode": "add_to_favorites", "media": "tvshow", "trakt_id": record['trakt_id']}, script=True, visible=validate_trakt()==False)
		
		menu.add(33060, {"mode": "set_default_view", "view": "tvshow"}, visible=validate_default_views)
		
		if record['year']:
			try:
				record['title'] = u"%s (%s)" % (record['title'], record['year'])
			except UnicodeDecodeError:
				record['title'] = u"%s (%s)" % (record['title'].decode("utf-8"), record['year'])
		
		plugin.add_menu_item({'mode': 'season_list', "imdb_id": record['imdb_id'],"slug": record['slug'], "tvdb_id": record['tvdb_id'], "tmdb_id": record['tmdb_id'], "title": record['title'], "year": record['year'], "fanart": record['backdrop_url']}, record, total_items=count, menu=menu, replace_menu=True, image=record['cover_url'], fanart=record['backdrop_url'])
	plugin.eod(VIEWS.TV_DEFAULT, 'tvshows')	
plugin.register(['tv_watchlist', 'tv_trending', 'tv_popular', 'tv_recommended', 'tv_custom_list', 'tv_search', 'tv_similar', 'tv_favorites', 'tv_collection'], tv_list)

def season_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	imdb_id = plugin.args['imdb_id']
	tvdb_id = plugin.args['tvdb_id']
	results = trakt.get_show_seasons(imdb_id, tvdb_id)
	if not results:
		return
	for record in results:
		if record['number'] > 0:
			menu = ContextMenu()
			season_id = record['ids']['trakt']
			if 'poster' in record:
				image = record['poster']
			else:
				image = ''
			fanart = plugin.get_arg('fanart')
			season = record['number']
			record = {"title": i18n(30057) % season}
			if validate_trakt():
				watched = trakt.get_watched_season(imdb_id, season, season_id)
				if watched is None: continue
				if watched: 
					record['playcount'] = 1
					record['overlay'] = 7
					menu.add("Mark Season Unwatched", {"mode": "set_unwatched", "media": "season", "id": season, "imdb_id": imdb_id}, visible=validate_trakt)

				else:
					menu.add(i18n(30058), {"mode": "set_watched", "media": "season", "id": season, "imdb_id": imdb_id}, visible=validate_trakt)
			menu.add(33061, {"mode": "set_default_view", "view": "season"}, visible=validate_default_views)
			query = {
				'mode': 'episode_list', 
				"imdb_id": imdb_id, 
				"tvdb_id": tvdb_id, 
				"season": season, 
				"season_id": season_id, 
				"fanart": fanart,
				"trakt_id": plugin.get_arg('trakt_id'),
				"slug": plugin.get_arg('slug')
			}
			plugin.add_menu_item(query, record, menu=menu, image=image, fanart=fanart)
	plugin.eod(VIEWS.SEASON_DEFAULT, "tvshows")
plugin.register('season_list', season_list)
	
def episode_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	if plugin.get_arg('slug') is not None:
		show = trakt.get_show_info(plugin.args['slug'])
		results = trakt.get_show_episodes(plugin.args['slug'], plugin.args['season'])
	else:
		show = trakt.get_show_info(plugin.args['imdb_id'])
		results = trakt.get_show_episodes(plugin.args['imdb_id'], plugin.args['season'])
	if validate_trakt():
		watched = trakt.get_watched_episodes(plugin.args['season_id'])
	else:
		watched = None
	if not results:
		return	
	count = len(results)
	for record in results:
		plugin.log(record)
		record = trakt.process_record(record, media='episode', watched=watched, show=show)
		if record is False: continue
		if record['episode'] == 0: continue
		if plugin.get_setting('show_unaired_episodes') is False and record['aired'] is False: continue
		menu = ContextMenu()
		record['showtitle'] = show['title']
		record['year'] = show['year']
		record['title'] = "%s. %s" % (record['episode'], record['title'])
		record['imdb_id'] = plugin.args['imdb_id']
		if record['playcount'] == 0:
			menu.add(30041, {"mode": "set_watched", "media": "episode", "id": record['trakt_id'], "imdb_id": record['imdb_id'], "season": record['season'], "episode": record['episode']})
		else:
			if plugin.get_setting('hide_watched_episodes') == "true" : continue
			record['overlay'] = 7
			menu.add(30042, {"mode": "set_unwatched", "media": "episode", "id": record['trakt_id'], "imdb_id": record['imdb_id'], "season": record['season'], "episode": record['episode']})
		menu.add(33062, {"mode": "set_default_view", "view": "episode"}, visible=validate_default_views)
		
		if record['aired'] is False:
			formater = "[COLOR %s]%sx%s. %s - %s[/COLOR]" 
			subs = (UNAIRED_COLOR, record['season'], record['episode'], record['air_date'], record['title'])
			record['title'] = formater % subs
			plugin.add_menu_item({'mode': 'unaired_episode', "showtitle": record['showtitle'], "season": record['season'], "episode": record['episode']}, record, menu=menu, image=record['cover_url'], fanart=plugin.args['fanart'])
			continue
		else:
			hash_id = plugin.get_hash_id(record['imdb_id'], record['season'], record['episode'])
			if plugin.has_resume_point(hash_id):
				formater = u"[COLOR %s]%sx%s.[/COLOR] %s [COLOR %s][B]»[/B][/COLOR]"
				subs = (RESUME_COLOR, record['season'], record['episode'], record['title'], RESUME_COLOR)
			else:
				formater = "%sx%s. %s - %s" 
				subs = (record['season'], record['episode'], record['air_date'], record['title'])
		
		record['title'] = formater % subs
		

		plugin.add_video_item({'mode': 'play_episode', "display": record['title'], "imdb_id": record['imdb_id'], "tmdb_id": record['tmdb_id'], "year": record['year'], "showtitle": record['showtitle'], "season": record['season'], "episode": record['episode']}, record, total_items=count, menu=menu, image=record['cover_url'], fanart=plugin.args['fanart'])
	plugin.eod(VIEWS.EPISODE_DEFAULT, 'tvshows')
plugin.register('episode_list', episode_list)	

def tv_calendar():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()	
	results = trakt.get_calendar_shows()
	if validate_trakt():
		watched = trakt.get_watched_history('shows')
	else:
		watched = []
	count = len(results)
	for record in results:
		
		record = trakt.process_record(record, media='episode')
		if record['season'] == 0 or record['episode']== 0: continue
		if validate_trakt() and watched:
			if record['imdb_id'] in watched:
				if record['season'] in watched[record['imdb_id']]:
					record['playcount'] = 1 if record['episode'] in watched[record['imdb_id']][record['season']] else 0
					if plugin.get_setting('hide_watched_episodes') == "true" and record['playcount'] == 1: continue
		menu = ContextMenu()
		menu.add("Find Similar Shows", {"mode": "tv_similar", "imdb_id": record['imdb_id']})
		if record['playcount'] == 0:
			menu.add(30041, {"mode": "set_watched", "media": "episode", "id": record['trakt_id'], "imdb_id": record['imdb_id'], "season": record['season'], "episode": record['episode']})
		else:
			record['overlay'] = 7
			menu.add(30042, {"mode": "set_unwatched", "media": "episode", "id": record['trakt_id'], "imdb_id": record['imdb_id'], "season": record['season'], "episode": record['episode']})
		menu.add(30044, {"mode": "season_list", "imdb_id": record['imdb_id'], "tvdb_id": record['tvdb_id'], "fanart": record['backdrop_url']})
		hash_id = plugin.get_hash_id(record['imdb_id'], record['season'], record['episode'])
		if plugin.has_resume_point(hash_id):
			record['title'] = u"[COLOR %s]%sx%s.[/COLOR] %s - %s [COLOR %s][B]»[/B][/COLOR]"% (RESUME_COLOR, record['season'], record['episode'], record['showtitle'], record['title'], RESUME_COLOR)
		else:
			record['title'] = "%sx%s. %s - %s" % (record['season'], record['episode'], record['showtitle'], record['title'])

		query = {'mode': 'tv_transmogrify', "display": record['title'], "imdb_id": record['imdb_id'], "tmdb_id": record['tmdb_id'], "year": record['year'], "showtitle": record['showtitle'], "season": record['season'], "episode": record['episode']}
		menu.add(30043, query, visible=validate_transmogrifier)
		query = {'mode': 'play_episode', "display": record['title'], "imdb_id": record['imdb_id'], "tmdb_id": record['tmdb_id'], "year": record['year'], "showtitle": record['showtitle'], "season": record['season'], "episode": record['episode']}

		menu.add(33062, {"mode": "set_default_view", "view": "episode"}, visible=validate_default_views)		
		plugin.add_video_item(query, record, total_items=count, image=record['cover_url'], fanart=record['backdrop_url'], menu=menu)
	plugin.eod(VIEWS.EPISODE_DEFAULT, 'tvshows')	
plugin.register('tv_calendar', tv_calendar)

def movie_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	if plugin.mode ==		'movie_watchlist'  or validate_trakt() is False:
		watchlist = []
	else:
		watchlist = trakt.get_watchlist_movies(simple=True)
	
	if plugin.mode ==		'movie_favorites':
		results = trakt.get_favorites('movie')
	elif plugin.mode ==		'movie_collection':
		results = trakt.get_collected_movies()
	elif plugin.mode ==		'movie_watchlist':
		results = trakt.get_watchlist_movies()
		if not results: return
		regex = re.compile("^(A )|(An )|(The )", re.IGNORECASE)
		def sort_results(title):
			title = regex.sub('', title['movie']['title'], re.IGNORECASE)
			return title.lower()
		results = sorted(results, key=lambda x: x['movie']['title'])
	elif plugin.mode ==		'movie_trending':
		results = trakt.get_trending_movies()
	elif plugin.mode ==		'movie_popular':
		results = trakt.get_popular_movies()
	elif plugin.mode ==		'movie_recommended':
		results = trakt.get_recommended_movies()
	elif plugin.mode ==		'movie_custom_list':
		results = trakt.get_custom_list(plugin.args['slug'], 'movie')
		if not results: return
		regex = re.compile("^(A )|(An )|(The )", re.IGNORECASE)
		def sort_results(title):
			title = regex.sub('', title['movie']['title'], re.IGNORECASE)
			return title.lower()
		results = sorted(results, key=lambda x: x['movie']['title'])
	elif plugin.mode == 	'movie_search':
		query = plugin.get_property('search.query.refesh')
		if query:
			plugin.clear_property('search.query')
			plugin.clear_property('search.query.refesh')
		else:
			query = plugin.dialog_input(i18n(30059))
		if query is None:
			plugin.clear_property("search.query")
			return
		plugin.set_property('search.query', query)
		results = trakt.search(query, 'movie')
	elif plugin.mode == 	'movie_similar':
		results = trakt.get_similar_movies(plugin.args['imdb_id'])
	if validate_trakt(): watched = trakt.get_watched_history('movies')
	if not results:
		return
	count = len(results)	
	for record in results:
		record = trakt.process_record(record, media='movie')
		menu = ContextMenu()
		menu.add(30046, {"mode": "movie_similar", "imdb_id": record['imdb_id']})
		movie_title = record['title']
		if validate_trakt() and watched:
			if 'imdb' in watched and record['imdb_id'] in watched['imdb']:
				record['playcount'] = 1
				record['overlay'] = 7
				menu.add(30042, {"mode": "set_unwatched", "media": "movie", "id": record['imdb_id']})
			else:
				menu.add(30041, {"mode": "set_watched", "media": "movie", "id": record['imdb_id']})
		if plugin.mode ==	'movie_favorites':
			menu.add(33065, {"mode": "delete_from_favorites", "media": "movie", "title": record['title'], "trakt_id": record['trakt_id']}, script=True, visible=validate_trakt()==False)
		else:
			menu.add(33066, {"mode": "add_to_favorites", "media": "movie", "trakt_id": record['trakt_id']}, script=True, visible=validate_trakt()==False)
				
		if plugin.args['mode']=='movie_watchlist':
			menu.add(30037, {"mode": "movie_delete_from_watchlist", "imdb_id": record['imdb_id'], "name": movie_title}, script=True, visible=validate_trakt)
		else:
			if record['imdb_id'] in watchlist:
				record['title'] = '[COLOR %s]%s[/COLOR]' %  (WATCHLIST_COLOR, record['title'])
			menu.add(30038, {"mode": "movie_add_to_watchlist", "imdb_id": record['imdb_id']}, script=True, visible=validate_trakt)
			
		if plugin.args['mode']=='movie_custom_list':
			menu.add(30039, {"mode": "delete_from_custom_list", "media": "movie", "imdb_id": record['imdb_id'], "slug": plugin.args['slug'], "name": record['title']}, script=True, visible=validate_trakt)
		else:
			menu.add(30040, {"mode": "add_to_custom_list", "media": "movie", "imdb_id": record['imdb_id']}, script=True, visible=validate_trakt)	
		query = {'mode': 'movie_transmogrify', "imdb_id": record['imdb_id'], "tmdb_id": record['tmdb_id'], "year": record['year'], "title": movie_title }
		menu.add(30043, query, visible=validate_transmogrifier)
		hash_id = plugin.get_hash_id(record['imdb_id'])
		has_resume = plugin.has_resume_point(hash_id)
		if record['year']:
			try:
				if has_resume:
					record['title'] = u"%s [COLOR %s](%s) [B]»[/B][/COLOR]" % (record['title'], RESUME_COLOR, record['year'])
				else:
					record['title'] = u"%s (%s)" % (record['title'], record['year'])
			except UnicodeDecodeError:
				if has_resume:
					record['title'] = u"%s [COLOR %s](%s) [B]»[/B][/COLOR]" % (record['title'].decode("utf-8"), RESUME_COLOR, record['year'])
				else:
					
					record['title'] = u"%s (%s)" % (record['title'].decode("utf-8"), record['year'])
		menu.add(33063, {"mode": "set_default_view", "view": "movie"}, visible=validate_default_views)
		
		plugin.add_video_item({'mode': 'play_movie', "imdb_id": record['imdb_id'], "tmdb_id": record['tmdb_id'], "year": record['year'], "title": movie_title}, record, menu=menu, total_items=count, image=record['cover_url'], fanart=record['backdrop_url'])
	plugin.eod(VIEWS.MOVIE_DEFAULT, 'movies')
plugin.register(['movie_watchlist', 'movie_trending', 'movie_popular', 'movie_recommended', 'movie_custom_list', 'movie_similar', 'movie_search', 'movie_favorites', 'movie_collection'], movie_list)

def set_default_view():
	name, id = plugin.get_view()
	if not id:
		plugin.error_message(i18n(33067), i18n(33068)) 
		return
	if plugin.args['view'] == 'tvshow':
		plugin.set_setting('default_tvshow_view', str(id))
		plugin.notify( i18n(33069), name)
		
	elif plugin.args['view'] == 'season':
		plugin.set_setting('default_season_view', str(id))
		plugin.notify( i18n(33070), name)
	
	elif plugin.args['view'] == 'episode':
		plugin.set_setting('default_episode_view', str(id))
		plugin.notify( i18n(33071), name)	
	
	elif plugin.args['view'] == 'movie':
		plugin.set_setting('default_movie_view', str(id))
		plugin.notify( i18n(33072), name)
	
	elif plugin.args['view'] == 'folder':
		plugin.set_setting('default_folder_view', str(id))
		plugin.notify( i18n(33073), name)
		
	elif plugin.args['view'] == 'list':
		plugin.set_setting('default_list_view', str(id))
		plugin.notify( i18n(33074), name)	
	

plugin.register('set_default_view', set_default_view)

def add_to_favorites():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	title = trakt.save_favorite(plugin.args['media'], plugin.args['trakt_id'])
	if title:
		plugin.notify(i18n(33019), i18n(33077) % title)
	else:
		plugin.notify('Failure', 'See log for details')	

plugin.register('add_to_favorites', add_to_favorites)


def delete_from_favorites():
	ok = plugin.dialog_confirm(i18n(33079), i18n(30076), plugin.args['title'])
	if ok:
		from dudehere.routines.trakt import TraktAPI
		trakt = TraktAPI()
		trakt.delete_favorite(plugin.args['media'], plugin.args['trakt_id'])
		plugin.notify(i18n(33019), i18n(33078) % plugin.args['title'])
		plugin.refresh()

plugin.register('delete_from_favorites', delete_from_favorites)


def toggle_watched():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	re_watchlist = False
	if plugin.mode == 'set_watched':
		watched = True
		if plugin.args['media'] == 'episode' or plugin.args['media'] == 'season':
			watchlist = trakt.get_watchlist_tvshows(simple=True)
			re_watchlist = plugin.args['imdb_id'] in watchlist
	else:
		watched = False
	if plugin.args['media'] == 'season':
		response = trakt.set_watched_state(plugin.args['media'], plugin.args['imdb_id'], watched, plugin.args['id'])
	else:
		response = trakt.set_watched_state(plugin.args['media'], plugin.args['id'], watched)
	plugin.log(response)
	if re_watchlist: trakt.add_to_watchlist('shows', plugin.args['imdb_id'], id_type='imdb')
	hash_id = plugin.get_hash_id(plugin.get_arg('imdb_id',''),plugin.get_arg('season', ''),plugin.get_arg('episode', ''))
	plugin.clear_resume_point(hash_id)
	plugin.notify(i18n(33019), i18n(30061) if watched == True else in18(30062))
	plugin.refresh()
plugin.register(['set_watched', 'set_unwatched'], toggle_watched)	

def set_watched(media, imdb_id, season=None, episode=None):
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	if media == 'episode':
		re_watchlist = False
		watchlist = trakt.get_watchlist_tvshows(simple=True)
		re_watchlist = imdb_id in watchlist
		episode =trakt.get_episode_details(imdb_id, season, episode, None)
		trakt_id = episode['trakt_id']
		trakt.set_watched_state(media, trakt_id, True)
		if re_watchlist: trakt.add_to_watchlist('shows', imdb_id, id_type='imdb')
	plugin.refresh()

def custom_list_menu():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	lists = trakt.get_custom_lists()
	media = 'tv' if plugin.mode == 'tv_custom_lists' else 'movie'
	DB.connect()
	results = DB.query("SELECT slug FROM lists WHERE media=?", [media], force_double_array=True)
	DB.disconnect()
	sync_lists = [l[0] for l in results]
	plugin.add_menu_item({'mode': 'new_custom_list', "media": media}, {"title": '***New Custom List***'}, image=ARTWORK+'/create_trakt_list.jpg')
	for list in lists:
		menu = ContextMenu()
		if list['ids']['slug'] in sync_lists:
			display = "[COLOR %s]%s[/COLOR]" % (SYNC_COLOR, list['name'])
			menu.add(30048, {"mode": "unsync_list", "slug": list['ids']['slug'], "name": list['name']}, script=True, visible=validate_advanced)
		else:
			display = list['name']
			menu.add(30049, {"mode": "sync_%s_list" % media, "slug": list['ids']['slug'], "name": list['name']}, script=True, visible=validate_advanced)
		
		menu.add(30050, {"mode": "delete_custom_list", "slug": list['ids']['slug'], "name": list['name']}, script=True)
		plugin.add_menu_item({"mode": media + "_custom_list", 'slug': list['ids']['slug'], "media": media}, {"title": display}, menu=menu, image=ARTWORK+'/create_trakt_list.jpg')
	plugin.eod(VIEWS.LIST)
plugin.register(['tv_custom_lists', 'movie_custom_lists'], custom_list_menu)

def new_custom_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	name = plugin.dialog_input(i18n(30072))
	if name:
		response = trakt.create_custom_list(name)
		if 'ids' in response.keys():
			plugin.notify(i18n(33019), i18n(30073), image=ARTWORK + 'trakt.png')
		else:
			plugin.notify(i18n(33020), i18n(30074), image=ARTWORK + 'trakt.png')
		plugin.refresh()
plugin.register('new_custom_list', new_custom_list)

def delete_custom_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	ok = plugin.dialog_confirm(i18n(30075), i18n(30076), plugin.args['name'])
	if ok:
		response = trakt.delete_custom_list(plugin.args['slug'])
		if response:
			plugin.refresh()
		else:
			plugin.notify(i18n(33020), i18n(30074), image=ARTWORK + 'trakt.png')

plugin.register('delete_custom_list', delete_custom_list)

def delete_from_custom_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	ok = plugin.dialog_confirm(i18n(30077), i18n(30076), plugin.args['name'])
	if plugin.args['media'] == 'movie':
		media = 'movies'
	else:
		media = 'shows'
	if ok:
		response = trakt.delete_from_custom_list(plugin.args['media'], plugin.args['slug'], plugin.args['imdb_id'])
		plugin.refresh()
		if response['deleted'][media]==1:
			plugin.notify(i18n(33019), i18n(30078), image=ARTWORK + 'trakt.png')
		elif response['not_found'][media]==1:
			plugin.notify(i18n(33028), i18n(30079), image=ARTWORK + 'trakt.png')
		else:
			plugin.notify(i18n(33020), i18n(30074), image=ARTWORK + 'trakt.png')
plugin.register('delete_from_custom_list', delete_from_custom_list)

def add_to_custom_list():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	lists = trakt.get_custom_lists()
	options = [lists[index]['name'] for index in xrange(len(lists))]
	index = plugin.dialog_select(i18n(30080), options)
	if plugin.args['media'] == 'movie':
		media = 'movies'
	else:
		media = 'shows'
	if index:
		slug = lists[index]['ids']['slug']
		id = plugin.args['imdb_id']
		id_type = 'imdb'
		response = trakt.add_to_custom_list(plugin.args['media'], slug, id, id_type)
		if response['added'][media]==1:
			plugin.notify(i18n(33019), i18n(30081), image=ARTWORK + 'trakt.png')
		elif response['existing'][media]==1:
			plugin.notify(i18n(33028), 'Already exists in list', image=ARTWORK + 'trakt.png')
		else:
			plugin.notify(i18n(33020), i18n(30074), image=ARTWORK + 'trakt.png')
plugin.register('add_to_custom_list', add_to_custom_list)	

def add_watchlist():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	if plugin.mode == 'tv_add_to_watchlist':
		media = 'shows'
	else:
		media = 'movies'
	id = plugin.args['imdb_id']
	id_type = 'imdb'
	response = trakt.add_to_watchlist(media, id, id_type=id_type)
	if response['added'][media]==1:
		plugin.refresh()
		plugin.notify(i18n(33019), i18n(30082), image=ARTWORK + 'trakt.png')
	elif response['existing'][media]==1:
		plugin.notify(i18n(33028), i18n(30083), image=ARTWORK + 'trakt.png')
	else:
		plugin.notify(i18n(33020), i18n(30074), image=ARTWORK + 'trakt.png')
plugin.register(['tv_add_to_watchlist', 'movie_add_to_watchlist'], add_watchlist)

def delete_from_watchlist():
	from dudehere.routines.trakt import TraktAPI
	print plugin.args
	trakt = TraktAPI()
	if plugin.mode == 'tv_delete_from_watchlist':
		media = 'shows'
	else:
		media = 'movies'
	ok = plugin.dialog_confirm(i18n(30084), i18n(30076), plugin.args['name'])
	if ok:
		id = plugin.args['imdb_id']
		id_type = 'imdb'
		response = trakt.delete_from_watchlist(media, id, id_type=id_type)

		if response['deleted'][media]==1:
			plugin.refresh()
			plugin.notify(i18n(33019), i18n(30085), image=ARTWORK + 'trakt.png')
		elif response['not_found'][media]==1:
			plugin.notify(i18n(33028), i18n(30086), image=ARTWORK + 'trakt.png')
		else:
			plugin.notify(i18n(33020), i18n(30076), image=ARTWORK + 'trakt.png')
		
plugin.register(['tv_delete_from_watchlist', 'movie_delete_from_watchlist'], delete_from_watchlist)

def show_help():
	content = vfs.read_file(vfs.join(LANGUAGE_PATH, 'help.txt'))
	plugin.show_textbox(i18n(30088), content)
plugin.register('show_help', show_help)

def advanced_mode():
	mode = 'false' if validate_advanced() else 'true'
	for i in range(1,8):
		plugin.set_setting('advanced_mode_%s' % i, mode)
	plugin.refresh()
plugin.register('advanced_mode', advanced_mode)

def reset_ugottoc():
	from dudehere.routines.window import Window
	class ResetWindow(Window):
		def __init__(self, title):
			super(self.__class__,self).__init__(title,width=700, height=300, columns=4, rows=6, quiet=True)
			self.draw()
			
		def set_info_controls(self):
			
			label = self.create_label(i18n(33031))
			self.add_label(label, 0, 0, columnspan=4, pad_x=15, pad_y=10)
			
			label = self.create_label(i18n(33032))
			self.add_label(label, 1, 0, columnspan=4, pad_x=15, pad_y=10)
			
			label = self.create_label(i18n(33033))
			self.add_label(label, 2, 0, columnspan=4, pad_x=15, pad_y=10)
			
			label = self.create_label(i18n(33034))
			self.add_label(label, 3, 0, columnspan=4, pad_x=15, pad_y=10)
			
			label = self.create_label(i18n(33035))
			self.add_label(label, 4, 0, columnspan=2, pad_x=15, pad_y=10)
			
			self.create_input('reset', _alignment=2)
			self.add_object('reset', 4, 1, columnspan=2)
			
			self.create_button('cancel', i18n(33036))
			self.add_object('cancel',  5, 1)
			
			self.create_button('confirm', i18n(33037))
			self.add_object('confirm',  5, 2)
			
		def confirm(self):
			if self.get_value('reset') != 'RESET':
				plugin.notify(i18n(33039), i18n(33040))
				return
			ok = plugin.dialog_confirm(i18n(33041), i18n(33042), i18n(33043))
			if ok:
				vfs.rm(DATA_PATH, quiet=True, recursive=True)
				self.close()
				plugin.exit()
			else:
				self.close()
			self.close()
		
	reset = ResetWindow(i18n(33044))
	reset.set_object_event('focus', 'reset')
	reset.set_object_event('down', 'reset', 'confirm')
	reset.set_object_event('up', 'confirm', 'reset')
	reset.set_object_event('left', 'confirm', 'cancel')
	reset.set_object_event('right', 'cancel', 'confirm')
	reset.set_object_event('up', 'cancel', 'reset')
	reset.set_object_event('action', 'cancel', reset.close)
	reset.set_object_event('action', 'confirm', reset.confirm)
	reset.show()
plugin.register("reset_ugottoc", reset_ugottoc)

def clear_cache(ok=False):
	if not ok:
		ok = plugin.dialog_confirm("Clear Cache", "Are you sure?", "This is your delete you cached data")
	if ok:
		from dudehere.routines.trakt import TraktAPI
		trakt = TraktAPI()
		trakt.delete_cache()
plugin.register('clear_cache', clear_cache)

def authorize_trakt():
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	response = trakt.do_authorization()
	if response:
		plugin.notify(i18n(33018), i18n(33019), image=ARTWORK + "trakt.png")
	else:
		plugin.notify(i18n(33018), i18n(33020), image=ARTWORK + "trakt.png")
	
plugin.register('authorize_trakt', authorize_trakt)	

def color_picker():
	colors = vfs.read_file(vfs.join(ROOT_PATH, 'resources/colors.txt')).splitlines()
	display = []
	for color in colors:
		color = color.lower()
		display.append("[COLOR %s]%s[/COLOR]" % (color, color))
	index = plugin.dialog_select(i18n(30089), display)
	if not index: return
	color = colors[index].lower()
	plugin.set_setting('custom_color_%s' % plugin.args['type'], color)
plugin.register('color_picker', color_picker)

def open_settings():
	xbmcaddon.Addon(id=plugin.args['addon_id']).openSettings()
plugin.register(['ugottoc_settings', 'urlresolver_settings', 'transmogrifier_settings'], open_settings)

def manage_walter():
	plugin.run_command('RunAddon("service.walter.sobchak")')
plugin.register('manage_walter', manage_walter)

def manage_transmogrifier():
	plugin.run_command('RunAddon("service.transmogrifier")')
plugin.register('manage_transmogrifier', manage_transmogrifier)

def quick_search():
	import time
	query = plugin.dialog_input(i18n(30094))
	if query is None: return
	from dudehere.routines.scrapers import ScraperPool
	Scraper = ScraperPool(load=['alluc_api'])
	Scraper._start_time = time.time()
	results = Scraper.get_scraper_by_index(0).quick_search(query)
	Scraper.process_results(results)
	raw_url = Scraper.select_stream()
	if raw_url:
		resolved_url = Scraper.resolve_url(raw_url)
	else: return
	if not resolved_url: return
	plugin.play_stream(resolved_url, metadata={"title": i18n(30094), "cover_url": ""}, title=query)
	
plugin.register('quick_search', quick_search)



def on_playback_stop():
	data = plugin.get_stream_stop_times()
	media = 'episode' if plugin.mode in ['play_episode'] else 'movie'
	refresh = False if  plugin.is_playlist() else True
	hash_id = plugin.get_hash_id(plugin.get_arg('imdb_id',''),plugin.get_arg('season', ''),plugin.get_arg('episode', ''))
	if data['percent'] >= WATCH_PERCENT:
		if media == 'episode':
			plugin.set_watched('episode', plugin.get_arg('showtitle',''), plugin.get_arg('year',''), plugin.get_arg('season',''), plugin.get_arg('episode',''))
		else:
			plugin.set_watched('movie', plugin.get_arg('title',''), plugin.get_arg('year',''))
		
		plugin.clear_resume_point(hash_id)
		#refresh = False	
	else:
		plugin.set_resume_point(hash_id)
		refresh = False
		
	if refresh:
		xbmc.sleep(1000)
		plugin.refresh()
	
	plugin_url = plugin.get_property('Resume.Page')
	plugin.clear_property('Resume.Page')
	if  plugin_url.startswith('plugin://') is False:
		plugin_url = "plugin://" + plugin_url
	plugin.execute_url(plugin_url)	
			
plugin.on_playback_stop = on_playback_stop

def unaired_episode():
	plugin.notify('Unaired Episode!', 'Season %s Episode %s has not aired yet!' %(plugin.args['season'], plugin.args['episode']), timeout=3000)
	
plugin.register('unaired_episode', unaired_episode)

def play_episode():
	from dudehere.routines.scrapers import ScraperPool
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	Scraper = ScraperPool(load=['alluc_api', 'pvr', 'local', 'transmogrifier'], cache_results=plugin.get_setting('enable_result_caching')=="true")
	imdb_id = trakt.query_id('tmdb', plugin.args['tmdb_id']) if plugin.args['imdb_id'] == 'None' else plugin.args['imdb_id']
	title = plugin.args['showtitle']
	display = plugin.args['display']
	season = int(plugin.args['season'])
	episode = int(plugin.args['episode'])
	year = int(plugin.args['year'])
	resolved_url = Scraper.search_tvshows(title, season, episode, year, imdb_id)
	if not resolved_url: return
	if validate_transmogrifier_streaming():
		from dudehere.routines.transmogrifier import TransmogrifierAPI
		TM = TransmogrifierAPI()
		resolved_url = TM.get_streaming_url(resolved_url, host=Scraper.hostname)
	metadata = trakt.get_episode_details(imdb_id, season, episode)
	plugin.play_stream(resolved_url, metadata=metadata, title=display)
plugin.register('play_episode', play_episode)

def play_movie():
	from dudehere.routines.scrapers import ScraperPool
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	Scraper = ScraperPool(load=['alluc_api', 'local', 'transmogrifier'], cache_results=plugin.get_setting('enable_result_caching')=="true")
	imdb_id = trakt.query_id('tmdb', plugin.args['tmdb_id']) if plugin.args['imdb_id'] == 'None' else plugin.args['imdb_id']
	title = plugin.args['title']
	year = plugin.args['year']
	metadata = trakt.get_movie_details(imdb_id)
	resolved_url = Scraper.search_movies(title, year, imdb_id=imdb_id)
	if not resolved_url: return
	if validate_transmogrifier_streaming():
		from dudehere.routines.transmogrifier import TransmogrifierAPI
		TM = TransmogrifierAPI()
		resolved_url = TM.get_streaming_url(resolved_url, host=Scraper.hostname)
	plugin.play_stream(resolved_url, metadata=metadata)
plugin.register('play_movie', play_movie)

def watch_stream():
	from dudehere.routines.scrapers import ScraperPool
	from dudehere.routines.trakt import TraktAPI
	trakt = TraktAPI()
	Scraper = ScraperPool(load=['alluc_api', 'pvr', 'local', 'transmogrifier'], cache_results=plugin.get_setting('enable_result_caching')=="true")
	imdb_id = plugin.args['imdb_id']
	if plugin.args['media'] == 'episode':
		season = int(plugin.args['season'])
		episode = int(plugin.args['episode'])
		metadata = trakt.get_episode_details(imdb_id, season, episode)
		year = metadata['year']
		title = metadata['showtitle']
		resolved_url = Scraper.search_tvshows(title, season, episode, year, imdb_id)
	else:
		metadata = trakt.get_movie_details(imdb_id)
		year = metadata['year']
		title = metadata['title']
		resolved_url = Scraper.search_movies(title, year, imdb_id=imdb_id)
	if not resolved_url: return
	plugin.play_stream(resolved_url, metadata=metadata)
plugin.register('watch_stream', watch_stream)


if __name__ == '__main__':
	plugin.run()
