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

import os, sys, pygame, pygame.font, pygame.image,subprocess, sys, time
from pygame.locals import *
sys.path.insert(0, '../CONF/')
import urllib2
from DefResAndSysFile import *
from DefCheckEnvFile import DefCheckEnv
Sys=DefSystem()
Resolution=DefResolution()

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


pygame.init()



finished = 0


Emu_Media=str(sys.argv[1])
Media=str(sys.argv[2])


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


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/8)
WHERE_XBAR=Space_bar
WHERE_YBAR=(Y/2) - (YBAR/2)


fond = pygame.transform.scale(pygame.image.load("download.png").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('../MEDIA/font.ttf', FontSize)
GoToOne=0




if Sys == "Darwin":
	Liste_media='SNAP','WHEEL','DOCS','ROMS'
else :
	Liste_media='SNAP','WHEEL','DOCS','ROMS','VIDEO'
 
if Emu_Media == "LIBRETRO":
	Liste_media='RPI23'
	GoToOne=1
if Emu_Media == "BIOS":
	Liste_media='ROMS'
	Media='BIOS'
	GoToOne=1

if GoToOne == 1:
	if Emu_Media == "LIBRETRO":
		Ext_Media=".so"
		url = "http://media.pyrharckade.io/"+ Emu_Media + "/" + Liste_media + "/" + Media + Ext_Media
		PathToDir='../BIN/'+ Emu_Media + '/'

	if Media == "retroarch":
		Ext_Media=""
		url = "http://media.pyrharckade.io/"+ Emu_Media + "/" + Liste_media + "/" + Media + Ext_Media
		PathToDir='../BIN/'+ Emu_Media + '/'
	if Media == "config_libretro":
		Ext_Media=".cfg"
		url = "http://media.pyrharckade.io/"+ Emu_Media + "/" + Liste_media + "/" + Media + Ext_Media
		PathToDir='../BIN/'+ Emu_Media + '/'



	if  Emu_Media == "BIOS":
		url = "http://media.pyrharckade.io/"+ Emu_Media + "/" + Liste_media + "/" + Media + Ext_Media
		PathToDir='../MEDIA/BIOS/ROMS/'
	
	text1 = "Check : " +  Emu_Media_url + "/" + Liste_media + "/" + Media + Ext_Media
	text2 = font.render(text1, True, pygame.Color("white"), pygame.Color("black"))
	PyrScreen.blit(text2,((Space_bar),(X/2)))
	PyrScreen.blit(fond, (0,0))

	if not os.path.exists(PathToDir + Media + Ext_Media):
		try:
			urllib2.urlopen(url)
			ERR_TEST='OK'
		except urllib2.HTTPError, e:
			ERR_TEST=str(e.code)
	else:
		ERR_TEST = '404'
		u = urllib2.urlopen(url)
		meta = u.info()
		file_size = int(meta.getheaders("Content-Length")[0])
		file_size_exist=getSize(PathToDir + Media + Ext_Media)
		if str(file_size) == str(file_size_exist):
			ERR_TEST = '404'
			text1 = "Check : " +  Emu_Media + "/" +  Media + Ext_Media + " : OK" 
			text2 = font.render(text1, True, pygame.Color("white"), pygame.Color("black"))
			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(PathToDir):
			os.makedirs(PathToDir)
		u = urllib2.urlopen(url)

		meta = u.info()
		file_size = int(meta.getheaders("Content-Length")[0])

		file_name = url.split('/')[-1]
		
		f = open(PathToDir + 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),(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 ' + 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),(X/2)))
			pygame.display.update()
			
		else:
			print PathToDir  + "/" + 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()




















































	

else:
	for Type_Media in (Liste_media):
	#for Type_Media in ('SNAP','WHEEL','DOCS','ROMS','VIDEO'): 
		print(Type_Media)
		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,((Space_bar),(X/2)))
		PyrScreen.blit(fond, (0,0))


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

		file_name = url.split('/')[-1]


		if not os.path.exists('../MEDIA/' + Emu_Media + '/' + Type_Media + "/" + Media + Ext_Media):
			try:
				urllib2.urlopen(url)
				ERR_TEST='OK'
			except urllib2.HTTPError, e:
				ERR_TEST=str(e.code)
		else:
			ERR_TEST = '404'
			u = urllib2.urlopen(url)
			meta = u.info()
			file_size = int(meta.getheaders("Content-Length")[0])
			file_size_exist=getSize('../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),(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('../MEDIA/' + Emu_Media + '/' + Type_Media):
				os.makedirs('../MEDIA/' + Emu_Media + '/' + Type_Media)
			u = urllib2.urlopen(url)

			meta = u.info()
			file_size = int(meta.getheaders("Content-Length")[0])
			
			f = open('../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),(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),(X/2)))
				pygame.display.update()
				
			else:
				print '../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()






