import sys,copy,os,re

import ned_commandLine as commandline
import ned_fastaHelper as fastaHelper


class anchorHelper():
	def __init__(self):
		self.data = {"anchorScore":[]}
		cmdline = commandline.CommandLine()
		self.options = cmdline.loadIniFile(os.path.join(os.path.dirname(os.path.realpath(__file__)),"../settings/utilities.ini"))
		

	def runAnchor(self,fastaPath,outputPath):
		cmd = self.options["anchor"] + " "
		cmd += ""+ fastaPath + " " 
		cmd += "-d " + os.path.dirname(self.options["anchor"]) + " "
		cmd += "> " + outputPath + " "
		
		os.popen(cmd)

	def parseAnchor(self,resultsPath):
		anchorData = open(resultsPath).read().strip().split("\n")
		
		for line in anchorData:
			if line[0] != "#":
				
				self.data["anchorScore"].append(float(line.split()[2]))
	
	
	def getAnchorScores(self,accession):
		if os.path.exists(self.options["anchor"]):
			fastaDir = os.path.join(self.options['uniprot_dir'],"fasta")
			fastaPath = os.path.join(fastaDir,accession + '.fasta')
			
			outputPath = os.path.join(self.options["anchor_dir"],os.path.basename(fastaPath) + ".anchor")
			
			fastahelper = fastaHelper.fastaHelper()
			fastahelper.fetchSequence(accession,fastaDir)
			
			if not os.path.exists(outputPath):
				self.runAnchor(fastaPath,outputPath)
		
			self.parseAnchor(outputPath)
	


if __name__ == "__main__":	
	for line in open("/Applications/Bioware/Datasets/SLiMSearch2/human/id.list").read().split("\n"):
		print line
		anchorRun = anchorHelper()
		anchorRun.getAnchorScores(line.strip())

"""
fastaPath = sys.argv[1]
outputPath = os.path.join(anchorRun.options["anchor_dir"],os.path.basename(fastaPath) + ".anchor")

if not os.path.exists(outputPath):
	anchorRun.runAnchor(fastaPath,outputPath)
	
anchorRun.parseAnchor(outputPath)"""