from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.ConfigList import ConfigList
from Components.config import config, ConfigSubsection, ConfigYesNo
from Components.Console import Console
from Screens.Console import Console as Screen_Console
from Screens.MessageBox import MessageBox
from Components.Sources.List import List
from Plugins.Plugin import PluginDescriptor
from os import path as os_path, system as os_system
from enigma import eConsoleAppContainer, evfd, getDesktop
from time import sleep as time_sleep

from __init__ import _

from GlobalFunctions import MC_MessageBox, MC_ChoiceBox
from Plugins.Extensions.Aafpanel.plugin import command

# Plugins
from MC_AudioPlayer import MC_AudioPlayer
from MC_VideoPlayer import MC_VideoPlayer
from MC_RadioPlayer import MC_RadioPlayer
from MC_PictureViewer import MC_PictureViewer
from MC_WeatherInfo import WeatherPlugin
from MC_Settings import MC_Settings
from MC_WebRadioFS import WebradioScreenBrowser
from MC_FileBrowser import MC_FileBrowser
from MC_AppleTrailer import MC_AppleTrailer
from MC_MyVideo import MC_MyVideo

emu = "none"
cemu = "none"

config.plugins.MediaCenter = ConfigSubsection()
config.plugins.MediaCenter.Enabled = ConfigYesNo(default=False)
config.plugins.mc_playing = ConfigSubsection()
config.plugins.mc_playing.Enabled = ConfigYesNo(default=False)

boxversion = command('cat /etc/model')

class DMC_MainMenu(Screen):
	def __init__(self, session):
		global emu, cemu
		Screen.__init__(self, session)
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()
		evfd.getInstance().vfd_write_string("MEDIACENTER")
		Console().ePopen(("/bin/umount -fl `mount | grep fuse | grep rarfs | grep -v '/dev/' | cut -d ' ' -f3`; killall -9 rarfs"))
		Console().ePopen(("/bin/umount -fl `mount | grep fuse | grep -v '/dev/' | cut -d ' ' -f3`; /bin/umount -fl `mount | grep iso9660 | cut -d ' ' -f3`; killall -9 rarfs fusesmb curlftpfs"))

		self.container = eConsoleAppContainer()
		self.container.execute('echo 3 > /proc/sys/vm/drop_caches')

		cemu = ''
		cem = open('/var/etc/autostart/start-config')
		ce = cem.readlines()
		cem.close()
		for line in ce:
			if line.find("emucontrol=") > -1:
				cemu = line.split('=')
				cemu = cemu[1].strip()
				cemu = cemu.replace("\n", "")
				cemu = cemu.replace('"', "")
		cemuck = cemu.split(' ')
		cemuck = cemuck[0]

		if cemuck.find('y') > -1:
			print "[MC_plugin] cemuck", cemuck
			
			checkactive = command("emu.sh active")
			if checkactive != '':
				infoname = command("emu.sh infoname")
				self.container = eConsoleAppContainer()
				self.container.execute('emu.sh halt')
				evfd.getInstance().vfd_write_string( infoname + " Stop" )
#				time_sleep(2)

		evfd.getInstance().vfd_write_string("MEDIACENTER")
		config.plugins.MediaCenter.Enabled = ConfigYesNo(default=True)
		self.whichPlugin = "None"

		list = []
		if config.plugins.mc_globalsettings.showaudioplayer.value is True:
			list.append((_("My Music"), "MC_AudioPlayer", "menu_music", "50"))
		if config.plugins.mc_globalsettings.showvideoplayer.value is True:
			list.append((_("My Videos"), "MC_VideoPlayer", "menu_video", "50"))
		if config.plugins.mc_globalsettings.showpictureviewer.value is True:
			list.append((_("My Pictures"), "MC_PictureViewer", "menu_pictures", "50"))	
		#if config.plugins.mc_globalsettings.showmultimediathek.value is True:
			#list.append((_("Multi Mediathek"), "MultiMediathek", "menu_multimediathek", "50"))
		if config.plugins.mc_globalsettings.showappletrailer.value is True:
			list.append((_("Apple Trailer"), "MC_AppleTrailer", "menu_appletrailer", "50"))
		if config.plugins.mc_globalsettings.showmyvideo.value is True:
			list.append((_("MyVideo"), "MC_MyVideo", "menu_myvideo", "50"))
		if config.plugins.mc_globalsettings.showvlcplayer.value is True:
			list.append((_("Vlc Player"), "VlcPlayer", "menu_vlcplayer", "50"))
		if config.plugins.mc_globalsettings.showfilebrowser.value is True:
			list.append((_("Filebrowser"), "MC_FileBrowser", "menu_browser", "50"))
		if boxversion.upper() == 'UFS912' or boxversion.upper() == 'AT7500':
			if config.plugins.mc_globalsettings.showinternetbrowser.value is True:
				list.append((_("Internet Browser"), "MC_Qtbrowser", "menu_qtbrowser", "50"))
		if config.plugins.mc_globalsettings.showradioplayer.value is True:
			list.append((_("Radio Player"), "MC_RadioPlayer", "menu_radio", "50"))
		if config.plugins.mc_globalsettings.showwebradio.value is True:
			list.append((_("WebRadioFS"), "MC_WebRadioFS", "menu_webradiofs", "50"))
		if config.plugins.mc_globalsettings.showweatherinfo.value is True:
			list.append((_("Weather Info"), "MC_WeatherInfo", "menu_weather", "50"))
		list.append((_("Settings"), "MC_Settings", "menu_settings", "50"))
		self["menu"] = List(list)

		self["actions"] = ActionMap(["OkCancelActions"],
		{
			"cancel": self.Exit,
			"ok": self.okbuttonClick
		}, -1)

		# start checking mayhemIII skinversion for updates
		self.onFirstExecBegin.append(self.checkmayhemIIIskin)

	def okbuttonClick(self):
		print "[MC_plugin] okbuttonClick"
		selection = self["menu"].getCurrent()
		if selection is not None:
			if selection[1] == "MC_VideoPlayer":
				self.session.open(MC_VideoPlayer)

			elif selection[1] == "MC_FileBrowser":
				self.session.open(MC_FileBrowser)

			elif selection[1] == "MC_PictureViewer":
				self.session.open(MC_PictureViewer)

			elif selection[1] == "MC_AudioPlayer":
				self.session.open(MC_AudioPlayer)

			elif selection[1] == "MC_RadioPlayer":
				ret = os_system("checknet")
				if ret == 0:
					self.session.open(MC_RadioPlayer)
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_Qtbrowser":
				ret = os_system("checknet")
				if ret == 0:
					if os_path.isfile("/var/bin/browser/browser") == True:
						self.session.openWithCallback(self.startQT, MC_MessageBox,_("Do you really want to start the Internetbrowser? Enigma2 will be killed and the Browser will be started!"), MC_MessageBox.TYPE_YESNO)
					else:
						self.whichPlugin = "qtbrowser" # set Plugin for self.downloadplugin
						self.session.openWithCallback(self.downloadPlugin, MC_ChoiceBox, title=_("QT Browser is not installed! Download it?"), list=[(_("Yes! Try to install to flash!"), "flash"), (_("No! Do not install!"), "no")])
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_AppleTrailer":
				ret = os_system("checknet")
				if ret == 0:
					self.session.open(MC_AppleTrailer)
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_MyVideo":
				ret = os_system("checknet")
				if ret == 0:
					self.session.open(MC_MyVideo)
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MultiMediathek":
				ret = os_system("checknet")
				if ret == 0:
					if os_path.exists("/usr/lib/enigma2/python/Plugins/Extensions/MultiMediathek/") == True:
						from Plugins.Extensions.MultiMediathek.plugin import *
						self.session.open(MultiMediathek)
					else:
						if os_path.exists("/var/swap/extensions/MultiMediathek/") == True:
							self.session.open(MC_MessageBox, _("The MultiMediathek plugin is installed in swap extensions but not mounted! Please restart your box so that the plugin will work correctly!"),  MC_MessageBox.TYPE_INFO)
						else:
							self.whichPlugin = "multimediathek" # set Plugin for self.downloadplugin
							if os_path.exists("/var/swap/extensions/"):
								self.session.openWithCallback(self.downloadPlugin, MC_ChoiceBox, title=_("MultiMediathek is not installed! Download it?"), list=[(_("Yes! Try to install to flash!"), "flash"), (_("Yes! Try to install to swap extensions!"), "swap"), (_("No! Do not install!"), "no")])
							else:
								self.session.openWithCallback(self.downloadPlugin, MC_ChoiceBox, title=_("MultiMediathek is not installed! Download it?"), list=[(_("Yes! Try to install to flash!"), "flash"), (_("No! Do not install!"), "no")])
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)


			elif selection[1] == "VlcPlayer":
				ret = os_system("checknet")
				if ret == 0:
					if os_path.exists("/usr/lib/enigma2/python/Plugins/Extensions/VlcPlayer/") == True:
						from Plugins.Extensions.VlcPlayer.plugin import main as vlcplugin
						vlcplugin(self.session)
					else:
						if os_path.exists("/var/swap/extensions/VlcPlayer/") == True:
							self.session.open(MC_MessageBox, _("The VLC Player plugin is installed in swap extensions but not mounted! Please restart your box so that the plugin will work correctly!"),  MC_MessageBox.TYPE_INFO)
						else:
							self.whichPlugin = "vlcplayer" # set Plugin for self.downloadplugin
							if os_path.exists("/var/swap/extensions/"):
								self.session.openWithCallback(self.downloadPlugin, MC_ChoiceBox, title=_("VLC Player is not installed! Download it?"), list=[(_("Yes! Try to install to flash!"), "flash"), (_("Yes! Try to install to swap extensions!"), "swap"), (_("No! Do not install!"), "no")])
							else:
								self.session.openWithCallback(self.downloadPlugin, MC_ChoiceBox, title=_("VLC Player is not installed! Download it?"), list=[(_("Yes! Try to install to flash!"), "flash"), (_("No! Do not install!"), "no")])

				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_WebRadioFS":
				ret = os_system("checknet")
				if ret == 0:
					self.session.open(WebradioScreenBrowser)
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_WeatherInfo":
				ret = os_system("checknet")
				if ret == 0:
					self.session.open(WeatherPlugin)
				else:
					self.session.open(MC_MessageBox, _("Start of application without internet not allowed."), type = MC_MessageBox.TYPE_INFO, timeout = 10)

			elif selection[1] == "MC_Settings":
				self.session.open(MC_Settings)

			else:
				self.session.open(MC_MessageBox,(_("Error: Could not find plugin %s\ncoming soon ... :)")) % (selection[1]),  MC_MessageBox.TYPE_INFO)

	def downloadPlugin(self, answer):
		if answer is not None and answer[1] != "no":
			ipkurl = command('cat /var/etc/ipkg/official-feed.conf | cut -d " " -f3')
			os_system('ipkg update')
			if answer[1] == "flash":
				if self.whichPlugin == "qtbrowser": # other package name for QTBrowser
					ipktype = "enigma2-plugin-browsers-"
				else:
					ipktype = "enigma2-plugin-mediacenter-"
				print "[MC_plugin] install %s to flash" % self.whichPlugin
			if answer[1] == "swap":
				ipktype = "enigma2-plugin-swapmediacenter-"
				print "[MC_plugin] install %s to swap extensions" % self.whichPlugin
			ipkpackage = command('cat /usr/lib/ipkg/cross | grep "Filename: ' + ipktype + '" | grep -m1 ' + self.whichPlugin + ' | sed "s/Filename: //"')
			print "[MC_plugin] download this package:", ipkpackage
			self.session.open(Screen_Console, title = _("installing plugin..."), cmdlist = ["ipkg install " + ipkurl +"/" + ipkpackage], closeOnSuccess = False)

	def checkmayhemIIIskin(self):
		actualversion = "4.0" # always add needed mayhemIII version here
		self.usemayhemIII = command('cat /etc/enigma2/settings | grep config.plugins.mc_globalsettings.currentskin.path | grep mayhemIII | tr "=" "\n" | tail -n 1')
		if self.usemayhemIII != "" and os_path.isfile(self.usemayhemIII): # check for actual mayhemIII and check for existing skin.xml
			print "[MC_plugin] current skin: mayhemIII detected!"
			self.mayhemIIIversion = command('cat ' + self.usemayhemIII + ' | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 4 | tail -n 1 | sed "s/v//"')
			print "[MC_plugin] mayhemIII version is:", self.mayhemIIIversion
			print "[MC_plugin] actual mayhemIII version is:", actualversion
			# Check that self.mayhemIIIversion has the correct format otherwise set an old version to download a new skin...
			if self.mayhemIIIversion is None or self.mayhemIIIversion == "":
				self.mayhemIIIversion = "1.0"
			if self.mayhemIIIversion[-2] != ".":
				self.mayhemIIIversion = "1.0"
			if float(self.mayhemIIIversion) < float(actualversion):
				print "[MC_plugin] WARNING: Please update your mayhemIII skin!"
				self.session.openWithCallback(self.updatemayhemIII, MC_ChoiceBox, title=_("MayhemIII not up to date! Update now?"), list=[(_("Yes! Try to update the skin!"), "yes"), (_("No! Do not update the skin!"), "no")])
				self.session.open(MC_MessageBox, _("The mayhemIII skin you are using is not up to date! Maybe it will cause errors! Please update your mayhemIII skin!"), type = MC_MessageBox.TYPE_INFO, timeout = 30)
			else: # check the correct mayhemIII size
				print "[MC_plugin] check correct mayhemIII resolution..."
				if getDesktop(0).size().width() == 720:
					print "[MC_plugin] detected e2-SD skin! No mayhemIII will work!"
					self.session.open(MC_MessageBox, _("In e2 you activated a SD skin but the MediaCenter skin is a mayhemIII skin! This skin has got another resolution and will not fit correctly on your TV screen!\nPlease choose a KingSize- or an HD-enigma2 skin or activate the Default Skin in the MediaCenter settings!"), type = MC_MessageBox.TYPE_INFO, timeout = 30)
				else:
					isHDorKS = command('cat ' + self.usemayhemIII + ' | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 2 | tail -n 1')
					e2skin = ""
					if getDesktop(0).size().width() == 1024 and isHDorKS == "MayhemIII-HD" :
						e2skin = "KingSize"
					elif getDesktop(0).size().width() == 1280 and isHDorKS == "MayhemIII-KS" :
						e2skin = "HD"
					if e2skin != "":
						print "[MC_plugin] wrong mayhemIII size detected!"
						#do NOT show MC Messagebox but normal Messagebox so that the whole Message will be shown with every e2 Skin
						self.session.open(MessageBox, _("The e2 skin you activated is %s size but the MediaCenter skin is the %s skin! This skin will not fit on your TV screen!\nPlease choose the same sized mayhemIII skin or the default skin in the MediaCenter settings!") % (e2skin,isHDorKS), type = MessageBox.TYPE_INFO)

	def updatemayhemIII(self, answer):
		if answer is not None and answer[1] != "no":
			ipkurl = command('cat /var/etc/ipkg/official-feed.conf | cut -d " " -f3')
			os_system('ipkg update')
			# hd or kingsize
			#cat /var/swap/mcskins/mayhemIIIHD/skin.xml | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 2 | tail -n 1
			# MayhemIII-HD
			# MayhemIII-KS
			# flash or swap
			#cat /var/swap/mcskins/mayhemIIIHD/skin.xml | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 3 | tail -n 1
			#SWAP
			#FLASH
			isFLASHorSWAP = command('cat ' + self.usemayhemIII + ' | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 3 | tail -n 1')
			isHDorKS = command('cat ' + self.usemayhemIII + ' | grep "XBMC Mod by Civer" | tr " " "\n" | head -n 2 | tail -n 1')
			
			if isFLASHorSWAP == "FLASH":
				ipktype = "enigma2-plugin-mediacenter-mayhem3"
			elif isFLASHorSWAP == "SWAP":
				ipktype = "enigma2-plugin-swapmediacenter-mayhem3"
			else:
				ipktype = ""
			if isHDorKS == "MayhemIII-HD":
				ipktype2 = "hd"
			elif isHDorKS == "MayhemIII-KS":
				ipktype2 = "ks"
			else:
				ipktype2 = ""
			if ipktype == "" or ipktype2 == "":
				print "[MC_plugin] ERROR Can not check skin-type!!! Aborting Update..."
				self.session.open(MC_MessageBox, _("Can not update the skin automatically! Please update the skin manually!"), type = MC_MessageBox.TYPE_INFO, timeout = 30)
			else: 
				print "[MC_plugin] checking ipk for: " + ipktype + ipktype2
				ipkpackage = command('cat /usr/lib/ipkg/cross | grep -m1 "Filename: ' + ipktype + ipktype2 + '" | sed "s/Filename: //"')
				packageversion = command('cat /usr/lib/ipkg/cross | grep -m1 "Filename: ' + ipktype + ipktype2 + '" | sed "s/Filename: //" | tr "_" "\n" | head -n 2 | tail -n1')
				print "[MC_plugin] package is:", ipkpackage
				print "[MC_plugin] package version is:", packageversion
				if float(self.mayhemIIIversion) >= float(packageversion):
					print "[MC_plugin] cancel update! Version on the server is older....!"
					self.session.open(MC_MessageBox, _("The mayhemIII skin on the server is older than your version! Canceling the update!"), type = MC_MessageBox.TYPE_INFO, timeout = 30)
				else:
					print "[MC_plugin] updating mayhemIII skin!"
					self.session.open(MC_MessageBox, _("Please restart your box so that the update will take effect!"), type = MC_MessageBox.TYPE_INFO)
					self.session.open(Screen_Console, title = _("updating skin..."), cmdlist = ["ipkg install -force-overwrite " + ipkurl +"/" + ipkpackage], closeOnSuccess = False)

	def startQT(self, answer):
		if answer == True:
			from Screens.Standby import TryQuitMainloop
			self.session.open(TryQuitMainloop, 20)

	def Exit(self):
		global emu, cemu

		self.session.nav.stopService()
		self.session.nav.playService(self.oldService)

		self.container = eConsoleAppContainer()
		self.container.execute('echo 3 > /proc/sys/vm/drop_caches')

		cemu = ''
		cem = open('/var/etc/autostart/start-config')
		ce = cem.readlines()
		cem.close()
		for line in ce:
			if line.find("emucontrol=") > -1:
				cemu = line.split('=')
				cemu = cemu[1].strip()
				cemu = cemu.replace("\n", "")
				cemu = cemu.replace('"', "")
		cemuck = cemu.split(' ')
		cemuck = cemuck[0]

		if cemuck.find('y') > -1:
			print "[MC_plugin] cemuck", cemuck
			
			checkactive = command("emu.sh active")
			if checkactive != '':
				infoname = command("emu.sh infoname")
				self.container = eConsoleAppContainer()
				self.container.execute('emu.sh unhalt')
				evfd.getInstance().vfd_write_string( infoname + " Start" )

		config.plugins.MediaCenter.Enabled = ConfigYesNo(default=False)
		config.plugins.MediaCenter.save()
		self.close()

def main(session, **kwargs):
	session.open(DMC_MainMenu)

def menu(menuid, **kwargs):
	if menuid == "mainmenu":
		return [(_("Media Center"), main, "dmc_mainmenu", 44)]
	return []

def Plugins(**kwargs):
	if config.plugins.mc_globalsettings.showinmainmenu.value == True and config.plugins.mc_globalsettings.showinextmenu.value == True:
		return [
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main),
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, where = PluginDescriptor.WHERE_MENU, fnc = menu),
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)]	
	elif config.plugins.mc_globalsettings.showinmainmenu.value == True and config.plugins.mc_globalsettings.showinextmenu.value == False:
		return [
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main),
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, where = PluginDescriptor.WHERE_MENU, fnc = menu)]
	elif config.plugins.mc_globalsettings.showinmainmenu.value == False and config.plugins.mc_globalsettings.showinextmenu.value == True:
		return [
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main),
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)]
	else:
		return [
			PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your " + boxversion, icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main)]
