"""
* 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 PatientsRecords
#
# \file    PatientsRecords.py
# \author  lina
# \date    2008-12-08
#
# User can create, delete patient records or view existing records
#
#----------------------------------------------------------------------------------

from mevis import *
from PythonQt import *


## 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;

## initDB is used to retrieve the data from patient records and show it
## in a table.
def initDB():
    myList = ctx.control("list");
    myList.clearItems();
    ##init DB
    queryString = "select lastName, firstName, dateofBirth, sex, MRO from Patients;";
    result = sendQuery(queryString);
    if result == -1:
      return;

    for item in result:
      lastName = item["lastname"];
      firstName = item["firstname"];
      DOB = item["dateofbirth"];
      sex = "M";
      if (item["sex"] == 1):
        sex = "F";
      MRO = item["mro"];
      myList.insertItem([""+lastName, ""+firstName, ""+str(MRO), ""+str(DOB), ""+sex]);
    if myList.currentItem() != None:
      selectChanged();   
    MLAB.log("retrieve and display Patient Records.");   

## this function is called when the user change the selection on the patients'
## record list
def selectChanged():
  myList = ctx.control("list");
  item = myList.selectedItem();
  if item != None:
    ctx.field("itemSelected").setValue(True);
    ctx.field("itemSelected").touch();
    currentPatient = item;
    ctx.field("PatientsName").setValue(item.text(1) + " " + item.text(0));
    ctx.field("PatientID").setValue(item.text(2));
    ctx.field("PatientsBirthDate").setValue(item.text(3));
    ctx.field("PatientsSex").setValue(item.text(4));
    
    parentM = context.parent();
    parentM.field("PatientsName").setValue(item.text(0) + "^" + item.text(1));
    parentM.field("PatientID").setValue(item.text(2));
    parentM.field("PatientsBirthDate").setValue(item.text(3));
    parentM.field("PatientsSex").setValue(item.text(4));
    
    title = "Patient: " + item.text(0) + "^" + item.text(1) + "   with MRO: " + item.text(2) + " DOB: " + item.text(3) + " " + item.text(4);
    ctx.window().setTitle(title);
    ctx.field("patientSelected").touch();
    return;
  else:
   ctx.field("itemSelected").setValue(False);
   ctx.field("patientSelected").touch();
  resetValues();
  
## reset the patient information
def resetValues():
  ctx.field("PatientsName").setValue("");
  ctx.field("PatientID").setValue("");
  ctx.field("PatientsBirthDate").setValue("");
  ctx.field("PatientsSex").setValue("");
  
  parentM = context.parent();
  parentM.field("PatientsName").setValue("");
  parentM.field("PatientID").setValue("");
  parentM.field("PatientsBirthDate").setValue("");
  parentM.field("PatientsSex").setValue("");
  ctx.window().setTitle("Angio-Localize angioLocalize");
  
## this function sets the values in gender combo Box: Male or Female 
def setItems():
    ctx.control("genderBox").setItems(["M","F"]);

## add the item to the listbox and Close dialog 
def closeOk():
    myList = ctx.control("list");
    firstName = ctx.field("FirstName").value;
    lastName = ctx.field("LastName").value;
    MRO = ctx.field("MRO").value;
    DOB = ctx.field("DOB").value;
    if (DOB.isdigit() == False):
      MLAB.showInformation("Make sure DOB's format is correct.", "", "MevisLab");
      return;
    gender = ctx.control("genderBox").currentText();
    sex = 0;
    if (gender == "F"):
      sex = 1;
    queryString = "INSERT INTO PATIENTS (PATIENTID, LASTNAME, FIRSTNAME, DATEOFBIRTH, SEX, MRO) VALUES(DEFAULT,";
    queryString = queryString + "'" + lastName + "'" + "," + "'" + firstName + "'" + ",";
    queryString = queryString + str(DOB) + "," + str(sex) + "," + "'" + str(MRO) + "'" + ");"
    result = sendQuery(queryString);
    if (result == -1):
      MLAB.showInformation("The record cannot be saved. make sure MRO does not exist in database.", "", "MevisLab");
      return;
    showGender = "M";
    if (gender == "F"):
      showGender = "F";
    myList.insertItem([""+lastName, ""+firstName, ""+MRO, ""+DOB, ""+showGender]);
    closeCancel();
   
## clear the patient record entry
def closeCancel():
    ctx.field("FirstName").setValue("");
    ctx.field("LastName").setValue("");
    ctx.field("MRO").setValue("");
    ctx.field("DOB").setValue("");
    ctx.control("genderBox").setCurrentItem(0);
    
## delete a patient in the database    
def delete():
    MRO = ctx.control("list").currentItem().text(2);
    queryString = "DELETE FROM PATIENTS WHERE mro = '" + MRO + "'";
    result = sendQuery(queryString); 
    if (result != -1):
      ctx.control("list").removeItem(ctx.control("list").currentItem());   
    else:
      MLAB.showInformation("The database operation deleting patient with MRO:" + ctx.control("list").currentItem().text(2) + " failed.", "", "MLAB");
    deletePatientInFile(MRO);
    selectChanged();
    
## show Help
def helpOnCreate():
    # Here is the framework for entering help information
    ctx.showHtmlHelp();
#//# 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

