# https://www.macports.org/install.php and run "sudo port install ImageMagick" as Imagick site suggests.
# "sudo easy_install lxml" to install the xml library on Mac.

# For images:
import os
import shutil
try:
	from urllib import urlretrieve
except:
	from urllib.request import urlretrieve

#For plist setup
from lxml import etree
import urllib

def setupIcons():
	print('Downloading...')
	urlretrieve('http://appserve.sharefaith.com/getAllIcons.php', os.path.expanduser('~/Downloads/icons.zip'))
	print('downloaded')
	icons = os.path.expanduser('~/Downloads/icons')
	try:
		shutil.rmtree(icons) #Remove the entire directory.
	except OSError:
		pass#ok
	os.system('cd ~/Downloads; unzip icons.zip && rm icons.zip')
	for img in os.listdir( icons ):
		if img[:2] == 'sf':
			print("processing %s" % (img,))
			#shutil.move( os.path.join( icons, img), os.path.join( icons, img[2:]) )
			#Transparent turns to black anyway in the ios app icon...
			#Careful icons like 0a5cf4dcb3c80252.jpg can be messed with some options.
			#TODO try making smaller with -strip!!! https://stackoverflow.com/questions/7261855/
			#os.system('convert -size 152x152 -colorspace RGB -quality 90 -alpha background -background black -antialias  ~/Downloads/icons/%s ~/Downloads/icons/%s' % (img, img[2:].replace('.png','.jpg')))
			#os.system('convert -size 152x152 -quality 90 -alpha background -background black -flatten ~/Downloads/icons/%s ~/Downloads/icons/%s' % (img, img[2:].replace('.png','.jpg')))
			os.system('convert -strip -size 152x152 -colors 256 -colorspace sRGB -quality 80 -alpha background -background black -flatten -define png:compression-level=9 -define png:format=8 ~/Downloads/icons/%s ~/Downloads/icons/%s' %(img, img[2:]))
			os.remove(os.path.join(icons,img))
	shutil.copy('ios/Sharefaith Churchapp/Sharefaith ChurchApp/Images.xcassets/AppIcon.appiconset/icon-152x152.png', os.path.expanduser('~/Downloads/icons/default.png'))
	os.system('convert -size 152x152 -quality 90 -alpha background -background black -flatten ~/Downloads/icons/default.png ~/Downloads/icons/default.jpg')
	print('ok, now drag icons in download folder into Xcode Supporting Files, group not folder reference mode.')

def setupPlist():
	print('Processing Plist icons list...')
	plist = 'ios/Sharefaith ChurchApp/Sharefaith ChurchApp/Sharefaith ChurchApp-Info.plist'
	root = etree.parse(plist)

	#Now add from the plist generated... All valid xml has one outer.
	try:
		latestIconXML =  '<plistxml>'+urllib.urlopen('http://appserve.sharefaith.com/userfiles/plist.txt').read() + '</plistxml>'
	except: #python3:
		latestIconXML =  '<plistxml>'+urllib.request.urlopen('http://appserve.sharefaith.com/userfiles/plist.txt').read().decode('utf-8') + '</plistxml>'


	#First remove the current alternate-icons for both ipad/iphone:
	for item in root.findall('//key'):
		if 'CFBundleAlternateIcons' == item.text:
			#print dir(item)
			for part in item.getnext().getchildren():
				part.getparent().remove(part)
			#All removed, add in new:
			#Create tree each time because append does move elements:
			latestTree = etree.fromstring(latestIconXML)
			skipDict = False
			for newone in latestTree.getchildren():
				if "key" == newone.tag:
					#print(newone.text) identifier
					if os.path.isfile( os.path.expanduser('~/Downloads/icons/%s.png' % (newone.text.strip(),) ) ):
						item.getnext().append( newone )
					else:
						print(newone.text+" has no icon and you should probably check that app.")
						skipDict = True #Skip one following <dict> tag
				elif "dict" == newone.tag:
					if not skipDict:
						item.getnext().append( newone )
					skipDict = False
	#Overwrite the file with updated icons:
	root.write(plist)

setupIcons()
setupPlist()
#try:
#	shutil.rmtree('ios/Sharefaith ChurchApp/Sharefaith ChurchApp/icons')
#except:
#	pass#ok
#shutil.copytree( os.path.expanduser('~/Downloads/icons'), 'ios/Sharefaith ChurchApp/Sharefaith ChurchApp/icons')
print('Done!');
