#!/usr/bin/env python
#-*- coding: utf-8 -*-
# pyrharckade 2 is a simple pygame front for PIMAME
# version: 2.0A
# guillaume@tuxme.net
# GPL Licence

import os, sys, pygame, pygame.font, pygame.image,subprocess, sys, time
from pygame.locals import *
import urllib2
import urllib
from DefResAndSysFile import *
from DefCheckEnvFile import DefCheckEnv
Sys=DefSystem()
import glob
Resolution=DefResolution()


def DownloadGraphical(Emu_Media,Media):

	def getSize(filename):
	    st = os.stat(filename)
	    return st.st_size

	finished = 0





	if Emu_Media == "BIOS":
		Ext_Media=".tar.bz2"

	if Emu_Media == "FBA" or Emu_Media == "CPS3" or Emu_Media == "GNGEO" or Emu_Media == "MAME" or Emu_Media == "CPS3":
		Emu_Media_url = "ARCADE"
	else:
		Emu_Media_url=Emu_Media


	### PROD
	pygame.init()
	Y,X=Resolution
	PyrScreen = pygame.display.set_mode(Resolution,FULLSCREEN)

	### TEST
	#Y,X=(800,600)
	#Resolution=(Y,X)
	#PyrScreen = pygame.display.set_mode(Resolution)




	Space_bar=20
	XBAR=(Y-(Y/Space_bar))
	YBAR=(X/10)
	WHERE_XBAR=Space_bar
	WHERE_YBAR=(Y/2) - (YBAR/2)


	if glob.glob("./BIN/download.png"):
		IMG_DL="./BIN/download.png"
		FONT_DL="./MEDIA/font.ttf"
		PATH_MEDIA="./MEDIA/"
	else:
		IMG_DL="download.png"
		FONT_DL="../MEDIA/font.ttf"
		PATH_MEDIA="../MEDIA/"
		
	fond = pygame.transform.scale(pygame.image.load(IMG_DL).convert(),Resolution)
	PyrScreen.blit(fond, (0,0))
	time.sleep(0.8)
	pygame.draw.rect(PyrScreen,(200,200,200),((WHERE_XBAR,WHERE_YBAR),(XBAR,YBAR)),0)
	FontSize = (X/10)
	font = pygame.font.Font(FONT_DL, (FontSize+10))




	if Sys == "Darwin":
		Liste_media='SNAP','WHEEL','DOCS','ROMS'
	else :
		Liste_media='SNAP','WHEEL','DOCS','ROMS','VIDEO'
	print("SYSTEM : " + (Sys))

	for Type_Media in (Liste_media): 
	#for Type_Media in ('SNAP','WHEEL','DOCS'): 



		if Type_Media == "SNAP" or Type_Media == "WHEEL":
			Ext_Media=".png"
		if Type_Media == "VIDEO":
			Ext_Media=".mpg"
		if Type_Media == "ROMS":
			Ext_Media=".zip"
		if Type_Media == "DOCS":
			Ext_Media=".txt"
		if Emu_Media == "BIOS":
			Ext_Media=".tar.bz2"
		if Emu_Media == "NES" and Type_Media=="ROMS":
			Ext_Media=".nes"
		if Emu_Media == "GAMEBOY" and Type_Media=="ROMS":
			Ext_Media=".gb"



		if Emu_Media == "FBA" or Emu_Media == "CPS3" or Emu_Media == "GNGEO" or Emu_Media == "MAME" or Emu_Media == "CPS3":
			Emu_Media_url = "ARCADE"
		else:
			Emu_Media_url=Emu_Media
			





		text1 = "Check : " +  Emu_Media_url + "/" + Type_Media+ "/" + Media + Ext_Media
		text2 = font.render(text1, True, pygame.Color("white"), pygame.Color("black"))
		#PyrScreen.blit(text2,((Y/2),(Y/2)))
		PyrScreen.blit(text2,((Space_bar),(X/2)))
		PyrScreen.blit(fond, (0,0))

		url = "http://media.pyrharckade.io/"+ Emu_Media_url + "/" + Type_Media+ "/" + Media + Ext_Media

		if Type_Media == "ROMS" and Emu_Media_url == "ARCADE": 
			Ext_Media=".zip"
			url = "http://www.arcadehits.net/downloads/tool.php?am=berzerking&Fichier=mame/" + Media + Ext_Media
			



		if Emu_Media == "SYS" and Type_Media=="ROMS":
			Ext_media=".csv"
			url="http://media.pyrharckade.io/SYS/ROMS/ROM_CONFIG_FILES.csv"
		print(url)

		file_name = url.split('/')[-1]
		print ( PATH_MEDIA + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media)

		if not os.path.exists(PATH_MEDIA + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media):
			TestCodeUrl=urllib.urlopen(url).getcode()
			if TestCodeUrl == 200:
			#try:
			#	urllib2.urlopen(url)
				ERR_TEST='OK'
			#except urllib2.HTTPError, e:
			#	ERR_TEST=str(e.code)
			else:
				ERR_TEST='404'
				

		else:
			ERR_TEST = '404'
			print (PATH_MEDIA + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media)
			u = urllib2.urlopen(url)
			meta = u.info()
			file_size = int(meta.getheaders("Content-Length")[0])
			file_size_exist=getSize(PATH_MEDIA + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media)
			if str(file_size) == str(file_size_exist):
				ERR_TEST = '404'
				text1 = "Check : " +  Emu_Media_url + "/" + Type_Media+ "/" + Media + Ext_Media + " : OK" 
				text2 = font.render(text1, True, pygame.Color("white"), pygame.Color("black"))
				#PyrScreen.blit(text2,(Space_bar,WHERE_YBAR+(YBAR*2)))
				PyrScreen.blit(text2,((Space_bar),(X/2)))
				pygame.draw.rect(PyrScreen,(120,38,38),((WHERE_XBAR,WHERE_YBAR),(XBAR,YBAR)),0)
				pygame.display.update()
				time.sleep(0.8)

			else:
				ERR_TEST = 'GO_TO_DL'
				print ("File Diff")

		if ERR_TEST != '404':
			continuer = 1
			if not os.path.exists(PATH_MEDIA + Emu_Media + '/' + Type_Media):
				os.makedirs(PATH_MEDIA + Emu_Media + '/' + Type_Media)
			u = urllib.urlopen(url)

			meta = u.info()
			file_size = int(meta.getheaders("Content-Length")[0])
			
			f = open(PATH_MEDIA + Emu_Media + '/' + Type_Media + '/' + file_name, 'wb')
			meta = u.info()
			file_size_dl = 0
			block_sz = 8192
			buffer=0
			#entry_info = 'Download ' + Type_Media + " in " + Emu_Media + " for " + Media


			pygame.display.update()


			while finished == 0:
				if file_size_dl ==  file_size:
					text2 = font.render(entry_info, True, pygame.Color("green"),pygame.Color("black"))
		        		#PyrScreen.blit(text2,(Space_bar,WHERE_YBAR+(YBAR*2)))

					PyrScreen.blit(text2,((Space_bar),(X/2)))
				#	pygame.display.update()
					time.sleep(0.8)
					break
					finished=1
				buffer = u.read(block_sz)

				file_size_dl += len(buffer)
				f.write(buffer)
				status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
				status = status + chr(8)*(len(status)+1)
				Progress=((XBAR*file_size_dl)/file_size)
				pygame.draw.rect(PyrScreen,(200,200,200),((WHERE_XBAR,WHERE_YBAR),(XBAR,YBAR)),0)
				pygame.draw.rect(PyrScreen,(120,38,38),((WHERE_XBAR,WHERE_YBAR),(Progress,YBAR)),0)
				Pourcent=100*file_size_dl/file_size

			#	pygame.display.update()

				entry_info = 'Download ' + Type_Media + " in " + Emu_Media + " for " + Media + " : " + str(Pourcent) + " %"

				text1 = entry_info
				text2 = font.render(entry_info, True, pygame.Color("white"), pygame.Color("black"))

				pygame.time.delay(40)

	#			pygame.draw.rect(PyrScreen,(200,200,200),((WHERE_XBAR,WHERE_YBAR),(XBAR,YBAR)),0)
				#PyrScreen.blit(fond, (0,0))
			#	pygame.display.update()
				#PyrScreen.blit(text2,(Space_bar,WHERE_YBAR+(YBAR*2)))
				PyrScreen.blit(text2,((Space_bar),(X/2)))
				pygame.display.update()
				
			else:
				print ( PATH_MEDIA + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media + ' : OK')
				f.close()
				#pygame.draw.rect(PyrScreen,(200,200,200),((WHERE_XBAR,WHERE_YBAR),(XBAR,YBAR)),0)
				PyrScreen.blit(fond, (0,0))
			#	pygame.display.update()
			pygame.display.update()






