"""
* 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 DSA2D
#/*!
# \file    DSA2D.py
# \author  LinaLiu
# \date    2009-12-10
#
# 
#*/
#----------------------------------------------------------------------------------

from mevis import *

from PythonQt import *
import time;


## Global varibles
filename = "";

## init the main window of DSA2D. hard coded the directory to browse and set the patient information
def initWindow():
  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("PatientID").setValue(ctx.parent().field("PatientID").value);
  ctx.field("OpenImage2.dicomBrowser.reload").touch();
  ctx.field("OpenImage2.previewLoad.autoLoad").touch();
  ctx.field("OpenImage2.imgLoad.autoLoad").touch();
## init Module set the initial settings of some sub macroModule
def initModule():
  ctx.field("Subimage.modifyX").setBoolValue(False);
  ctx.field("Subimage.modifyY").setBoolValue(False);
  ctx.field("Subimage.modifyX").touch();
  ctx.field("Subimage.modifyY").touch();
  ctx.field("Subimage.fullSize").touch();
  ctx.field("Subimage.modifyZ").setBoolValue(True);
  ctx.field("Subimage.sz").setDoubleValue(1);
  ctx.field("Subimage.apply").touch();
  ctx.field("ImgPropConvert1.changeWorldMatrix").setValue(False);
  ctx.field("View2D.ext.annotation.annotationUserBottomLeft").setValue("Timepoint: $(slice) \n$(sizex),$(sizey),$(sizec) \n$(voxelx),$(voxely) \n$(SeriesDescription)");
  ctx.field("View2D.ext.annotation.showOrientation").setValue("ANNO_ORIENTATION_OFF");
  ctx.field("View2D.ext.annotation.annotationMode").setValue("ANNO_MODE_USER");
  
## 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;

## When user specify a new image, retrieve the DicomTag values.  
def newImageName():
   ctx.field("DicomTagModify.tagName0").value = "PatientsName";
   ctx.field("DicomTagModify.tagName1").value = "PatientsBirthDate";
   ctx.field("DicomTagModify.tagName2").value = "PatientID";
   ctx.field("DicomTagModify.tagName3").value = "PatientsSex";
   ctx.field("DicomTagModify.tagName4").setValue("SeriesDescription");
   ctx.field("DicomTagModify.tagName5").setValue("Modality");
   ctx.field("DicomTagModify.getValues").touch();
   
   PatientN = ctx.field("DicomTagModify.tagValue0").value;
   PatientDOB = ctx.field("DicomTagModify.tagValue1").value;
   ID = ctx.field("DicomTagModify.tagValue2").value;
   Sex = ctx.field("DicomTagModify.tagValue3").value;
   if PatientN != ctx.field("PatientsName").value or PatientDOB != ctx.field("PatientsBirthDate").value or ID != ctx.field("PatientID").value or Sex != ctx.field("PatientsSex").value:
     details = "";
     if PatientN != ctx.field("PatientsName").value:
       details += "<br>PatientName in Dicom: <b>" + PatientN + "</b> versus <b>" +  ctx.field("PatientsName").value + "</b> in records.";
     if PatientDOB != ctx.field("PatientsBirthDate").value:
       details +=  "<br>PatientBirthDate in Dicom: <b>" + PatientDOB + "</b> versus <b>" +  ctx.field("PatientsBirthDate").value + "</b> in records."
     if ID != ctx.field("PatientID").value:
       details += "<br>PatientID in Dicom:<b>" + ID + "</b> versus <b>" +  ctx.field("PatientID").value + "</b> in records.";
     if Sex != ctx.field("PatientsSex").value:
       details += "<br>PatientSex in Dicom:<b>" + Sex + "</b> versus <b>" +  ctx.field("PatientsSex").value + "</b> in records.\n";
     answer = MLAB.showQuestion("The DICOM image info does not match patient's record. Do you want to replace the DICOM tags with patient's info in record?", details, "MeVisLab", ["OK", "Cancel"], 0);
     if answer == 1:
       msg = "The user canceled the operation when the patient record did not match that in database. The patient information in DICOM stays the same as follows:";
       msg =+ "Patient Name:" + PatientN + "  DOB: " + PatientDOB + "  ID:" + ID + "  Sex:" + Sex; 
       MLAB.log(msg);
       return;
     else:
       ##save the data into the image
       ctx.field("DicomTagModify.tagValue0").value = ctx.field("PatientsName").value;
       ctx.field("DicomTagModify.tagValue1").value = ctx.field("PatientsBirthDate").value;
       ctx.field("DicomTagModify.tagValue2").value = ctx.field("PatientID").value;
       ctx.field("DicomTagModify.tagValue3").value = ctx.field("PatientsSex").value;
       ctx.field("DicomTagModify.apply").touch();
       msg = "The user replaced the patient information in DICOM image with that in database\n";
       msg += "Patient information saved into DICOM are as follows:\n";
       msg += "Patient Name:" +  ctx.field("PatientsName").value;
       msg += "\nPatient Birth Date:" + ctx.field("PatientsBirthDate").value;
       msg += "\nPatient ID:" + ctx.field("PatientID").value;
       msg += "\nPatient Sex:" + ctx.field("PatientsSex").value;
       MLAB.log(msg);
   tempimage=ctx.field("DicomTagModify.output0").image();
   extent=tempimage.imageExtent();
   t=extent[4];
   if t != 1:
     ctx.field("SwapFlipDimensions.firstAxis").value = "z";
     ctx.field("SwapFlipDimensions.input0").connectFrom(ctx.field("DicomTagModify.output0"));
     ctx.field("ImgSave.input0").connectFrom(ctx.field("SwapFlipDimensions.output0"));
     ctx.field("View2D.inImage").connectFrom(ctx.field("SwapFlipDimensions.output0"));
   else:
     ctx.connectField("SetPageExt.input0", "DicomTagModify.output0");
     ctx.field("ImgSave.input0").connectFrom(ctx.field("ConcatImages.output0"));
     ctx.field("View2D.inImage").connectFrom(ctx.field("ConcatImages.output0"));
   ## pop up the saveImage window with the patient information as the window title
   wind = ctx.showWindow("SaveImgW");
   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();
   
## save the image to a file
def saveToFile():
  imageName = saveImageToFile(ctx.parent().field("PatientID").value, getFileName(),"");
  ctx.field("ImgSave.filename").value = imageName;
  ctx.field("ImgSave.save").touch();
  MLAB.log("The image: " + imageName + " has been saved in file system.");
  return imageName;

## get the formatted FileName: MRO(time) 
def getFileName():
  filename = ctx.parent().field("PatientID").value + "(" + time.strftime("%Y%m%d-%H%M%S") + ")";
  return filename;

## save the image to DB
def saveToDB(dir, descr, modality):
  query = "SELECT PatientID FROM Patients WHERE MRO = " + "'" + ctx.parent().field("PatientID").value + "'";
  result = sendQuery(query);
  if (result == "()"):
    return;
  patientID = 0;
  for item in result:
    patientID = item["patientid"];
  dir = dir.replace("\\", "/");
  query = "insert into images(imagetype, seriesDescr, modality, imageName,patientID) values(" + "1,'" + descr + "'," +  "'" + modality + "'," + "'" + dir + "'," + str(patientID) + ");";
  result = sendQuery(query);
  if (result == -1):
    return;
  MLAB.log("The image: " + dir +  " has been saved to the DB.");
  
## the callback function executed when user clicks approval and finish on SaveImage dialog
def clickOkOnSaveImgW():
  saveDir = saveToFile();
  descr = ctx.field("DicomTagModify.tagValue4").value;
  modality = ctx.field("DicomTagModify.tagValue5").value;
  saveToDB(saveDir, descr, modality);
  ctx.disconnectField("SetPageExt.input0");
  ctx.window().close();
  
## the Callback function executed when user clicks Cancel on SaveImage dialog
## the SetPageExt input will be disconnect from the ImageLoad and window is closed.
def clickCancelOnSaveImgW():
  ctx.disconnectField("SetPageExt.input0");
  ctx.window().close();  
  
## show help
def help():
  ctx.showHtmlHelp();
  
##  function holder to clean up DSA2D
def cleanUp():
  ctx.field("OpenImage2.previewLoad.close").touch();
  ctx.field("OpenImage2.imgLoad.close").touch();
#//# MeVis signature v1
#//# key: MFowDQYJKoZIhvcNAQEBBQADSQAwRgJBANEfsmYse2e1dRhkQ9AQbreCq9uxwzWLoGom13MNYmyfwoJqQOEXljLFAgw2eEjaT12G4CdqKWhRxh9ANP6n7GMCARE=:VI/mB8bT4u+mRtf/ru8yUQi8BzpaS3UeL2x62YxsUYnVqCWuLrVNLiukIIjnJMKQXlc8ezmgOIcVAV7pgvgKpQ==
#//# owner: MeVis
#//# date: 2009-06-10T04:12:25
#//# hash: vHSfj+Qt8xrIkDVP4W0Rep0YH6a3+MySa0+Cs+AoqEK/IbB+f5szwmyVTENOjzz/JEgm2t31FtHmUUMFcQg5VQ==
#//# MeVis end

