"""
Created December 2013

@author: zack.galbreath@kitware.com

This script loads Visomics-style analyses into the Arbor TreeStore database.

Requirements:
    - xmltodict (can be pip installed)
"""

from ArborFileManagerAPI import ArborFileManager
api = ArborFileManager()
api.initDatabaseConnection()

import json
import os
import sys
import xmltodict

# check that analysis directory has been passed in via the command line
if len(sys.argv) < 2:
  print sys.argv[0] + " <path/to/xml_dir>"
  sys.exit(1)

xml_dir = sys.argv[1]
xml_files = os.listdir(xml_dir)

for xml_file in xml_files:
  if not xml_file.endswith(".xml"):
    continue

  # find each matching pair of .xml & .R files
  analysis_name = xml_file[:-4]

  script_path = xml_dir + "/" + analysis_name + ".R"
  if not os.path.exists(script_path):
    print "Skipping %s because %s does not exist" % (analysis_name, script_path)
    continue

  # load their contents into a Python dictionary
  f = file(xml_dir + "/" + xml_file, "r")
  xml_contents = f.read()
  f.close()

  f = file(script_path, "r")
  script_contents = f.read()
  f.close()

  analysis_item = xmltodict.parse(xml_contents)
  analysis_item["analysis"]["script"] = script_contents

  # future proofing for other types of analyses
  analysis_item["analysis"]["type"] = "vtk_r"

  # use this dictionary to insert this analysis into the TreeStore
  api.newAnalysis(analysis_name, analysis_item)
  print "newAnalysis called for %s" % analysis_name

@@ -732,53 +732,249 @@
 h = 
-xml_dir + %22/%22 + analysis_name + %22.R%22%0A  if not
+%22%22%0A  analysis_type = %22%22%0A  r_script_path = xml_dir + %22/%22 + analysis_name + %22.R%22%0A  python_script_path = xml_dir + %22/%22 + analysis_name + %22.py%22%0A  if os.path.exists(r_script_path):%0A    script_path = r_script_path%0A    analysis_type = %22vtkr%22%0A  elif
  os.
@@ -985,16 +985,23 @@
 .exists(
+python_
 script_p
@@ -1002,24 +1002,101 @@
 ript_path):%0A
+    script_path = python_script_path%0A    analysis_type = %22vtkpython%22%0A  else:%0A
     print %22S
@@ -1114,18 +1114,36 @@
 because 
-%25s
+corresponding script
  does no
@@ -1153,17 +1153,16 @@
 xist%22 %25 
-(
 analysis
@@ -1170,22 +1170,8 @@
 name
-, script_path)
 %0A   
@@ -1489,57 +1489,8 @@
 ents
-%0A%0A  # future proofing for other types of analyses
 %0A  a
@@ -1528,15 +1528,21 @@
 %5D = 
-%22vtk_r%22
+analysis_type
 %0A%0A  

add ability to import python analyses