"""
* Copyright (c) 2009 Stanford University, School of Medicine All rights reserved. 
* 
* STANFORD ACADEMIC SOFTWARE LICENSE AGREEMENT 
* FOR AngioLocalize SOURCE CODE: 
* 
* 1.  This is a legal agreement between you, RECIPIENT, and STANFORD UNIVERSITY.  
*       By accepting, receiving, and using AngioLocalize.including any accompanying information, materials or 
*       manuals (Program), you are agreeing to be bound by the terms of this Agreement.  
*       If you do not agree to the terms of this Agreement, promptly return the Program to the STANFORD.

* 2.  STANFORD grants to RECIPIENT a royalty-free, nonexclusive, and nontransferable license to use the Program 
*       and accompanying source code furnished hereunder, upon the terms and conditions set out below. 
*       documentation and/or other materials provided with the distribution. 
* 3.  RECIPIENT acknowledges that the Program is a research tool still in the development stage and that 
*       it is being supplied as is, without any accompanying services, support or improvements from STANFORD.
* 4.  RECIPIENT agrees to use the Program solely for internal non-commercial purposes. 
* 5.  RECIPIENT may create derivatives and further transfer the Program under the following terms and conditions: 
*        A) Recipient agrees to not commercially exploit the Program and agrees all uses will be for non-commercial purposes; and,
*        B) Recipient may not mark any derivatives with the title of Program and may not to use iPad mark for any derivatives; and,
*        C) Recipient agrees to mark and acknowledge all derivatives as follows: "This is a derivative work based on AngioLocalize:
*           Frameless AVM localization with 2D Digital Subtraction Angiography (DSA) and 3D Rotational Angiography (DRA) Images developed
*           by Dimitre Hristov, Lina Liu.
*        D) Recipient agrees to make all improvements, enhancements and derivatives available under 
*           similar terms and conditions to the research community. 
* 6.   RECIPIENT warrants that RECIPIENT will not remove or export any part of the software or Program from the United 
*       States except in full compliance with all United States and other applicable laws and regulations.
* 7.  RECIPIENT will use the Program in compliance with all applicable laws, policies and regulations including, but not 
*       limited to, any approvals, informed consent and patient confidentiality principles.
* 8.   RECIPIENT will indemnify, hold harmless, and defend Stanford against any claim of any kind arising out of or
*       related to the exercise of any rights granted under this Agreement or the breach of this Agreement by RECIPIENT.
* 9.  Title and copyright to the Program and any associated documentation shall at all times remain with STANFORD, 
*       and RECIPIENT agrees to preserve same.
""" 
#----------------------------------------------------------------------------------
#! Macro module AngioExport
#/*!
# \file    AngioExport.py
# \author  LinaLiu
# \date    2009-12-10
#
# This is the module that exports CSO 
#*/
#----------------------------------------------------------------------------------

from mevis import *
import os;

##Global variables
wind = None 

## init export window
def initWindow():
  ctx.field("PatientID").setValue(ctx.parent().field("PatientID").value);
  ctx.field("PatientsName").setValue(ctx.parent().field("PatientsName").value);
  ctx.field("PatientsBirthDate").setValue(ctx.parent().field("PatientsBirthDate").value);
  ctx.field("PatientsSex").setValue(ctx.parent().field("PatientsSex").value); 
  ctx.field("CSOConvertToImage.copyInputImage").setBoolValue(True);
  patientID = getPatientRecordID();
  if (patientID != "0"):
    loadCSOList(patientID);

## load CSO list in GUI
def loadCSOList(patientID):
  CSOlist = ctx.controlDebug("list");
  CSOlist.clearItems();
  queryString = "select CSOId,  srcImage, filename from csolist, approvals where CSOId = objID AND objType = 1 and approvalStatus = 1 and approvals.patientID = csolist.patientID and csolist.patientID =  " + getPatientRecordID() + ";"
  result = sendQuery(queryString);
  if (str(result) != "()"):
    for item in result:
      CSOId = item["csoid"];
      srcImg = item["srcimage"];
      fileName = item["filename"];
      CSOlist.insertItem([str(CSOId), srcImg, fileName, "true"]);

## get the DB record ID for a patient given MRO number  
def getPatientRecordID():
  patientID = 0;
  if (ctx.field("PatientID").value == ""):
    return str(patientID);
  
  queryString = "SELECT PatientID FROM Patients WHERE MRO = " + "'" + ctx.field("PatientID").value + "'";
  result = sendQuery(queryString);
  
  if (str(result) != "()"):
    for item in result:
      patientID = item["patientid"];
  return str(patientID);

## send a query to the Database and return the result set
def sendQuery(query):
  ctx.field("DBConn.Statement").setValue(query);
  dbModule = ctx.module("DBConn");
  result = dbModule.call("sendQuery");
  if (result == -1):
    MLAB.logError("The following query to database failed. \n" + query + "\n.");
  dbModule.call("close");
  return result;

## export selected CSO  
def export(): 
  global wind;
  list = ctx.control("list");
  selectedItem = list.selectedItem();
  queryString = "Select imageName from images where ImageID = " + selectedItem.text(1);
  result = sendQuery(queryString);
  if(str(result) != "()"):
    for item in result:
      imageName = item["imagename"];
      imageLegalName = os.path.normpath(imageName + ".dcm");
      ctx.field("LoadApprovedReferenceImage.filename").setValue(imageLegalName);
      ctx.field("LoadApprovedReferenceImage.load").touch();
  fullName = os.path.normpath(selectedItem.text(2));    
  ctx.field("LoadApprovedStructure.fileName").setValue(fullName);
  ctx.field("LoadApprovedStructure.apply").touch();
  ctx.field("CSOConvertToImage.apply").touch();
  wind = ctx.showWindow("orthoView2DW");
  title = "Patient: " + ctx.field("PatientsName").value + "   with MRO: " + ctx.field("PatientID").value + " DOB: " + ctx.field("PatientsBirthDate").value + " " + ctx.field("PatientsSex").value;
  wind.setTitle(title);
  wind.showMaximized();

## cancel the OrthView2D window
def closeWin():
  global wind;
  if (wind != None):
    wind.close();
    wind = None;

## If user would like to save selected CSO, the DicomSave panel will be pop up
def save():
  closeWin();
  #ctx.module("DicomTool").showWindow();
  ctx.module("RTStructExportTool").showWindow();
  
## provides help for the user
def help():
  ctx.showHtmlHelp();

## cleanUp
def cleanUp():
  ctx.field("LoadApprovedReferenceImage.close").touch();
  ctx.field("LoadApprovedStructure.fileName").setValue("");
  ctx.field("LoadApprovedStructure.fileName").touch();

## export To RT Structure
def exportRTStruct():
  global wind;
  list = ctx.control("list");
  selectedItem = list.selectedItem();
  queryString = "Select imageName from images where ImageID = " + selectedItem.text(1);
  result = sendQuery(queryString);
  if(str(result) != "()"):
    for item in result:
      imageName = item["imagename"];
      imageLegalName = os.path.normpath(imageName + ".dcm");
      ctx.field("LoadApprovedReferenceImage.filename").setValue(imageLegalName);
      ctx.field("LoadApprovedReferenceImage.load").touch();
  fullName = os.path.normpath(selectedItem.text(2));    
  ctx.field("LoadApprovedStructure.fileName").setValue(fullName);
  ctx.field("LoadApprovedStructure.apply").touch();
  ctx.field("CSOToRTStructure.rtStructFile").setValue(ctx.field("rtStructFile").value);
  ctx.field("CSOToRTStructure.apply").touch();