# 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
	import urllib.request

#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'))
	urlretrieve('http://appserve.sharefaith.com/userfiles/churchList.txt', 'android/SFChurchApp/app/src/main/assets/churchList.txt')
	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 +dither -size 152x152 -colors 256 -colorspace sRGB -quality 80 -define png:compression-level=9 -define png:format=8 ~/Downloads/icons/%s ~/Downloads/icons/%s' %(img, img))
			shutil.copy(os.path.expanduser('~/Downloads/icons/'+img), 'android/SFChurchApp/app/src/main/res/drawable/'+img)
	
	#os.system('convert -size 152x152 -quality 90 -alpha background -background black -flatten ~/Downloads/icons/default.png ~/Downloads/icons/default.jpg')

def setupPlist():
	print('Processing Android Manifest...')
	manifest = 'android/SFChurchApp/app/src/main/AndroidManifest.xml'
	root = etree.parse(manifest)
	
	#Now add from the plist generated... All valid xml has one outer.
	#:android necessary for some attributes

	try:
		latestIconXML =  '<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sharefaith.thesharefaithapp">'+urllib.urlopen('http://appserve.sharefaith.com/userfiles/androidManifest.txt').read() + '</manifest>'
	except: #python3:
		latestIconXML =  '<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sharefaith.thesharefaithapp">'+urllib.request.urlopen('http://appserve.sharefaith.com/userfiles/androidManifest.txt').read().decode('utf-8')+ '</manifest>'
	
	latestIconXML = latestIconXML.replace('android:name="com.sharefaith.thesharefaithapp.SFMainActivity-', 'android:exported="true" android:name="com.sharefaith.thesharefaithapp.SFMainActivity_')
	#First remove the current alternate-icons for both ipad/iphone:
	ANDROID = '{http://schemas.android.com/apk/res/android}'
	#Remove all old:
	for item in root.findall('//activity-alias'):
		name = item.attrib[ANDROID+'name']
		if not name.endswith('default'):
			item.getparent().remove(item)
	#Add new:
	for item in root.findall('//activity-alias'):
		name = item.attrib[ANDROID+'name']
		#Now insert all after:
		if name.endswith('default'):
			latestTree = etree.fromstring(latestIconXML)
			for newone in latestTree.getchildren():
				if not newone.attrib[ANDROID+'name'].endswith('default'):
					item.getparent().append(newone)
			break
		else:
			print("Fail, no default in Android Manifest??")
	#Overwrite the file with updated icons:
	root.write(manifest)

setupIcons()
setupPlist()
print('Done!');
