# PyWAD is open-source software and consists of a set of plugins written in python for the WAD-Software medical physics quality control software. 
# The WAD Software can be found on https://github.com/wadqc
# 
# The pywad package includes plugins for the automated analysis of QC images for various imaging modalities. 
# PyWAD has been originaly initiated by Dennis Dickerscheid (AZN), Arnold Schilham (UMCU), Rob van Rooij (UMCU) and Tim de Wit (AMC) 
#
# Description:
# This plugin parses the daily QC report (XML format) generated by the Siemens biograph TOF PET-CT.
# To send the data from the scanner to dcm4chee a separate tool that has to be installed on the scanner has been developed by Rob van Rooij and Dennis Dickerscheid.

__version__ = '20082015'
__author__ = 'TdW'



from dicom import tag
import xml.etree.ElementTree as ET
import lxml.etree as etree

def print_xml(xmlroot):
   for child in xmlroot:
        print '=='*20
        print child.tag, child.attrib, child.text
        
        for subchild in child:
            print '\t', subchild.tag, subchild.attrib, subchild.text

            for value in subchild:
                print '\t\t', value.tag, value.attrib, value.text
                for subvalue in value:
                    print '\t\t\t', subvalue.tag, subvalue.attrib, subvalue.text

                    for subsubvalue in subvalue:
                        print '\t\t\t\t', subsubvalue.tag, subsubvalue.attrib, subsubvalue.text

def parseqcreport(data,results,**kwargs):
    params = kwargs.get('params', None)
    p = {}
    for param in params:
        p[param.tag] = (param.text,param.attrib)

    print p
    
    status_ok=True

    relevantfile = data.getAllInstances()[0]
    xmltext = relevantfile[tag.Tag(p.get('use_private_tag')[0].split(','))]

    root = etree.fromstring(xmltext.value)
    print_xml(root)
    
    datagroup = root.find('DataGroup')
    scandate = datagroup.get('DateTime')
    
    datapackages = root.findall(".//DataPackage[@Package_Name='ID_MODE']")
    for data in datapackages:
        status_ok=True
        kV=data.find(".//*/DataEntry[@Variable_Name='ID_VOLT']/LongVariable").get('Long_Value')
        mA=data.find(".//*/DataEntry[@Variable_Name='ID_CURRENT']/LongVariable").get('Long_Value')
        region=data.find(".//*/DataEntry[@Variable_Name='ID_REGION']/StringVariable").get('String_Value').replace('ID_','')

        row_n1_ok=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N1']/DataEntry").get('Variable_In_Spec')
        row_n2_ok=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N2']/DataEntry").get('Variable_In_Spec')
        row_n3_ok=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N3']/DataEntry").get('Variable_In_Spec')
        row_n1_kV_ok=data.find(".//*/DataSeries[@Series_Name='ID_VOLT']/*/DataEntry").get('Variable_In_Spec')
        status_ok = status_ok and row_n1_ok=='YES' and row_n2_ok=='YES' and row_n3_ok=='YES' and row_n1_kV_ok=='YES'

        # not present for all mA/kV combinations
        row_n1_sigma_element=data.find(".//*/DataSeries[@Series_Name='ID_SIGMA']/*/DataEntry")
        if row_n1_sigma_element is not None:
           row_n1_sigma_ok=row_n1_sigma_element.get('Variable_In_Spec')
           row_n1_sigma=row_n1_sigma_element.find('DoubleVariable').get('Double_Value')
           status_ok = status_ok and row_n1_sigma_ok=='YES'

        row_n1=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N1']/*/DoubleVariable").get('Double_Value')
        row_n2=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N2']/*/DoubleVariable").get('Double_Value')
        row_n3=data.find(".//*/DataSeries[@Series_Name='ID_WATER']/SeriesEntry[@Series_ID='ID_ROW_N3']/*/DoubleVariable").get('Double_Value')
        row_n1_kV=data.find(".//*/DataSeries[@Series_Name='ID_VOLT']/SeriesEntry/DataEntry/DoubleVariable").get('Double_Value')

        results.addChar('{0} {1}kV {2}mA'.format(region,kV,mA),'Passed' if status_ok else 'Failed',level=1)

        results.addFloat("{0} {1}kV {2}mA ROW_N1".format(region,kV,mA),row_n1,level=2,units='HU')
        results.addFloat("{0} {1}kV {2}mA ROW_N2".format(region,kV,mA),row_n2,level=2,units='HU')
        results.addFloat("{0} {1}kV {2}mA ROW_N3".format(region,kV,mA),row_n3,level=2,units='HU')
        if row_n1_sigma_element is not None:
           results.addFloat("{0} {1}kV {2}mA ROW_N1_sigma".format(region,kV,mA),row_n1_sigma,level=2,units='HU')
        results.addFloat("{0} {1}kV {2}mA ROW_N1_voltage".format(region,kV,mA),row_n1_kV,level=2,units='kV')
