#!/usr/bin/env python
#HEAD#########################################################
#
# Katana Framework | ktf.ktf                            
# Last Modified: 27/12/2016
#
#########################################################HEAD#

from core.Internal  import GetRootModules
from core.Function  import SYSTEM
from core.Design    import *
from core.Default   import FOLDER_KATANA
from core import Errors 

import importlib,argparse,sys,os,urllib2


CLASS_BANNER=DESIGN()
CLASS_BANNER.ktfktf()
SYSTEM      =SYSTEM()
printk      =printk()

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--import-module"        ,action='store_true',default=False,help=" Import a local module.")
parser.add_argument("-ir","--import-remote-module" ,action='store_true',default=False,help=" Import a remote module.")
parser.add_argument("-p", "--path"                 ,help=" Path or URL where is the module.")
parser.add_argument("-r", "--remove-module"        ,help=" Remove a module installed (-r CODENAME)")

args = parser.parse_args()


class ktf:
	def ImportModule(self,path):

		printk.inf("Importing Module")
		Loadingfile(path)
		try:
			printk.inf("Information Module")
			SYSTEM.Command_exe("Coping module to temp folder.             ","cp "+path+" "+FOLDER_KATANA+"tmp/",std=False)
			os.system("echo > "+FOLDER_KATANA+"tmp/__init__.py")
			path=os.path.basename(path).replace(" ","")
			path_import=path
			if path[len(path)-3:] == ".py" : path_import = path[:-3]
			ModuleToStart = importlib.import_module("tmp."+path_import) 
			init=ModuleToStart.init()

			printk.inf("Information Module")
			print "   |>Author           : "+init.Author
			print "   |>Version Script   : "+init.Version
			print "   |>Description      : "+init.Description
			print "   |>Code Name        : "+init.CodeName
			print "   |>Creation         : "+init.DateCreation
			print "   |>Last Modification: "+init.LastModification
			New = init.CodeName
			New = New.split("/")
			printk.inf("Installing module")
			printk.inf("Checking if exists module")
			
			for modules in GetRootModules().findall('module'):
				if modules.get('name') == init.CodeName:
					printk.err("the CodeName is already being used by another module.\n")
					exit()
			if os.path.isdir(FOLDER_KATANA+"modules/"+New[0]+"/") == False:
				SYSTEM.Command_exe("Crating a new category.                   ","mkdir "+FOLDER_KATANA+"modules/"+New[0]+"/",std=False)
				os.system("echo > "+FOLDER_KATANA+"modules/"+New[0]+"/__init__.py")
			
			SYSTEM.Command_exe("Coping file to Category folder.           ","cp "+FOLDER_KATANA+"tmp/"+path+" "+FOLDER_KATANA+"modules/"+New[0]+"/",std=False)
			printk.inf("Adding a module list")

			inFile = open(FOLDER_KATANA+'core/modules.xml', 'rw')
			data = inFile.readlines()
			LineNumber=0
			LastModuleofCategory=0
			for LineperLine in data:
				if LineperLine.find("name=\""+New[0]) >= 0:LastModuleofCategory=LineNumber+6
				LineNumber+=1
			InsertNewModule="""	<module name=\""""+init.CodeName+"""\">
        <version>"""+init.Version+"""</version>
        <author>"""+init.Author+"""</author>
        <category>"""+New[0]+"""</category>
        <filename>"""+path[:-3]+"""</filename>
        <description>"""+init.Description+"""</description>
    </module>
"""
			if LastModuleofCategory==0:LastModuleofCategory=LineNumber-1
			data.insert(LastModuleofCategory,InsertNewModule)
			inFile.close()
			outFile = open(FOLDER_KATANA+'core/modules.xml', 'w')
			outFile.writelines(data)
			outFile.close()
			printk.suff("Module installed")
			Space()
			os.system("rm "+FOLDER_KATANA+"tmp/*")

		except Exception as e:printk.err(str(e)+"\n")

	def RemoteImport(self,url):

		printk.inf("Downloading Module : "+url)
		d = urllib2.urlopen(url)
		outFile = open(FOLDER_KATANA+"tmp/temp_modules.py", 'w')
		outFile.writelines(d.read())
		outFile.close
		self.ImportModule(FOLDER_KATANA+"tmp/temp_modules.py")

if __name__=="__main__":
	ktf = ktf()
	if args.import_module         :ktf.ImportModule(args.path)
	elif args.import_remote_module:ktf.RemoteImport(args.path)
	else                          :printk.war("No Operation!, Use ktf.ktf -h.\n")
