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

import ConfigParser, os.path, StringIO, codecs, xml.dom.minidom, zipfile, re
from lib.BeautifulSoup import BeautifulSoup

def get_ini_info(ini, section, option, default=None):
	try:
		return ini.get(section, option)
	except ConfigParser.NoOptionError:
		return default

def get_infos(dirname, appspath):
	try:
		inifile = codecs.open(os.path.join(appspath, dirname, "App/AppInfo/appinfo.ini"), "r", "utf-8").read()
	except:
		return None
	
	if inifile[0:1] == u"\ufeff":
		inifile = inifile[1:]
		
	inifile = StringIO.StringIO(inifile.replace(";", "\;"))
			
	appinfo = ConfigParser.ConfigParser()
	appinfo.readfp(inifile)
	
	infos = {}
	
	try:
		infos["name"] = get_ini_info(appinfo, "Details", "Name", dirname)
		infos["parentname"] = get_ini_info(appinfo, "Framakey", "Name", dirname)
		infos["desc"] = get_ini_info(appinfo, "Details", "Description", "")
		infos["longdesc"] = BeautifulSoup(get_ini_info(appinfo, "Framakey", "LongDesc", "").replace("& ", "&amp; ")).prettify()
		
		try:
			xml.dom.minidom.parseString("<p>" + infos["longdesc"] + "</p>")
		except:
			infos["longdesc"] = ""
		if get_ini_info(appinfo, "Framakey", "Size", 0) == "":
			infos["size"] = 0
		else:
			infos["size"] = int(get_ini_info(appinfo, "Framakey", "Size", 0))
		infos["zipsize"] = 0
		
		infos["exe"] = get_ini_info(appinfo, "Control", "Start", dirname + ".exe")
		infos["dir"] = get_ini_info(appinfo, "Framakey", "Dir", dirname)
		infos["installdir"] = get_ini_info(appinfo, "Framakey", "Installdir", "")
		infos["dirsave"] = get_ini_info(appinfo, "Framakey", "Dirsave", "").split("|")
		while "" in infos["dirsave"]:
			infos["dirsave"].remove("")
		infos["dirsave"].append("Data")
	
		infos["version"] = get_ini_info(appinfo, "Version", "PackageVersion", 0)
		
		infos["author"] = get_ini_info(appinfo, "Details", "Publisher", "")
		infos["licence"] = get_ini_info(appinfo, "Framakey", "License", "")
		
		infos["framakey"] = get_ini_info(appinfo, "Details", "HomePage", "")
		infos["website"] = get_ini_info(appinfo, "Framakey", "AppWebsite", "")
		infos["framasoft"] = get_ini_info(appinfo, "Framakey", "FramasoftPage", "")
		
		infos["category"] = get_ini_info(appinfo, "Details", "Category", "Autres")
		infos["type"] = get_ini_info(appinfo, "Framakey", "Type", "apps").replace("webapps", "WebApps").replace("apps", "Applications")
	except ConfigParser.NoSectionError:
		return None
			
	
	if os.path.join(appspath, dirname, 'App/AppInfo/appicon_64.png'):
		infos["icon"] = os.path.join(appspath, dirname, 'App/AppInfo/appicon_64.png')
	else:
		infos["icon"] = "icons/autres.png"
	
	return infos

def get_package_infos(filename):
	try:
		package = zipfile.ZipFile(filename, 'r')
	except:
		raise IOError(filename + " n'est pas une archive zip.")
	
	try:
		app = re.match('(.+)_[^_]+', os.path.basename(filename)).group(1)
	except:
		app = filename
	
	try:
		inifile = package.read(app + '/App/AppInfo/appinfo.ini')
	except KeyError:
		raise IOError(filename + " ne contient pas de fichier appinfo.ini.")
	
	if inifile[0:3] == "\xef\xbb\xbf":
		inifile = inifile[3:]
	
	inifile = StringIO.StringIO(inifile)
	
	appinfo = ConfigParser.ConfigParser()
	appinfo.readfp(inifile)
	
	infos = {}
	
	try:
		infos["name"] = get_ini_info(appinfo, "Details", "Name", app)
		infos["parentname"] = get_ini_info(appinfo, "Framakey", "Name", app)
		infos["desc"] = get_ini_info(appinfo, "Details", "Description", "")
		infos["longdesc"] = BeautifulSoup(get_ini_info(appinfo, "Framakey", "LongDesc", "").replace("& ", "&amp; ")).prettify()
		
		try:
			xml.dom.minidom.parseString("<p>" + infos["longdesc"] + "</p>")
		except:
			infos["longdesc"] = ""
		
		infos["size"] = int(get_ini_info(appinfo, "Framakey", "Size", 0))
		infos["zipsize"] = os.path.getsize(filename)
		
		infos["exe"] = get_ini_info(appinfo, "Control", "Start", app + ".exe")
		infos["dir"] = get_ini_info(appinfo, "Framakey", "Dir", app)
		infos["installdir"] = get_ini_info(appinfo, "Framakey", "Installdir", "")
		infos["dirsave"] = get_ini_info(appinfo, "Framakey", "Dirsave", "").split("|")
		while "" in infos["dirsave"]:
			infos["dirsave"].remove("")
		infos["dirsave"].append("Data")
	
		infos["version"] = get_ini_info(appinfo, "Version", "PackageVersion", 0)
		
		infos["author"] = get_ini_info(appinfo, "Details", "Publisher", "")
		infos["licence"] = get_ini_info(appinfo, "Framakey", "License", "")
		
		infos["framakey"] = get_ini_info(appinfo, "Details", "HomePage", "")
		infos["website"] = get_ini_info(appinfo, "Framakey", "AppWebsite", "")
		infos["framasoft"] = get_ini_info(appinfo, "Framakey", "FramasoftPage", "")
		
		infos["category"] = get_ini_info(appinfo, "Details", "Category", "Autres")
		infos["type"] = get_ini_info(appinfo, "Framakey", "Type", "apps").replace("apps", "Applications").replace("webapps", "Webapps")
	except ConfigParser.NoSectionError:
		raise IOError("Le fichier appinfo.ini du paquet " + filename + " est mal formé.")
	
	try:
		f = open("cache/packages/" + app + ".png", "wb")
		f.write(package.read(app + '/App/AppInfo/appicon_64.png'))
		f.close()
		infos["icon"] = "cache/packages/" + app + ".png"
	except:
		infos["icon"] = "icons/install.png"
	
	return infos
