# 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__ = '01062015'
__author__ = 'DD'



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
    relevantfile = data.getAllInstances()[0]
    xmltext = relevantfile[tag.Tag(p.get('use_private_tag')[0].split(','))]

    root = etree.fromstring(xmltext.value)
    print_xml(root)

    #Sections:
    #Title
    title = root.find('aTitle')
    #Scandate
    scandate = root.find('bScandate')

    #Phantomparameters
    phantompars = root.find('cPhantomParameters')
    
    Isotope = phantompars.find('aIsotope').text
    results.addChar('Isotope',Isotope,level=1)

    AssayActivity = phantompars.find('bAssayActivity').find('aValue').text
    #+phantompars.find('bAssayActivity').find('bMeasure').text
    results.addFloat('AssayActivity',AssayActivity,level=1)

    AssayDatetime = phantompars.find('cAssayDateTime').text
    results.addChar('AssayDateTime',AssayDatetime,level=1)

    Volume = phantompars.find('dVolume').find('aValue').text
    results.addFloat('Volume',Volume,level=1)

    CalibrationFactor = phantompars.find('eCalibrationFactor').text
    results.addFloat('CalibrationFactor',CalibrationFactor,level=1)

    #Inputforcomputation
    compinput = root.find('dInputforComputation')



    SWversion = compinput.find('eICSSWVersion').text
    results.addChar('Software version',SWversion,level=2)
    Gantrytype =compinput.find('fSystemType').text
    results.addChar('Gantry type',Gantrytype,level=2)
    DailySinogram = compinput.find('aDailySinoLocation').text
    results.addChar('Sinogram location',DailySinogram,level=2)
    ProposedECFval = compinput.find('bProposedECFValue').find('aValue').text
    results.addFloat('Proposed ECF',ProposedECFval,level=2)

    LastPartialSetup = compinput.find('cLastSuccessfulSetup').find('LastSetupDateTime').text
    results.addChar('Last partial setup',LastPartialSetup,level=2)
    LastPartialSetupState = compinput.find('cLastSuccessfulSetup').find('LastSetupState').text
    results.addChar('Last partial setup state',LastPartialSetupState,level=2)

    LastFullSetup = compinput.find('hLastSuccessfulSetup').find('LastSetupDateTime').text
    results.addChar('Last full setup',LastPartialSetup,level=2)
    LastFullSetupState = compinput.find('hLastSuccessfulSetup').find('LastSetupState').text
    results.addChar('Last full setup state',LastPartialSetupState,level=2)


    Partialsetupenabled = compinput.find('gPartialSetupEnabled').text
    results.addChar('Partial setup enabled',Partialsetupenabled,level=2)
    ICSname =compinput.find('dICSName').text
    results.addChar('ICS name',ICSname,level=2)
    

    #Results
    sectionresults = root.find('eResults')

    SystemQualityResults = sectionresults.find('aSystemQualityResults').text
    results.addChar('System Quality Results',SystemQualityResults,level=1)
    QCPhantomActivity = sectionresults.find('aPhantomAgeResult').text
    results.addChar('QC Phantom Activity',QCPhantomActivity,level=1)
    

    #DetailedQCreport
    detres = root.find('fDetailedSystemQualityReport').find('aItem')

    BlockNoise = detres.find('aBlockNoise').find('cBlkValue').find('aValue').text
    results.addFloat('Block Noise',BlockNoise,level=2)
    BlockEfficiency =detres.find('bBlockEfficiency').find('cBlkValue').find('aValue').text
    results.addFloat('Block Efficiency',BlockEfficiency,level=2)
    MeasuredRandoms = detres.find('cMeasureRandoms').find('cBlkValue').find('aValue').text
    results.addFloat('Measured Randoms',MeasuredRandoms,level=2)
    ScannerEfficiency = detres.find('dScannerEfficiency').find('cBlkValue').find('aValue').text
    results.addFloat('Scanner Efficiency',ScannerEfficiency,level=2)
    ScatterRatio = detres.find('eScatterRatio').find('cBlkValue').find('aValue').text
    results.addFloat('Scatter Ratio',ScatterRatio,level=2)
    ECF = detres.find('fECF').find('cBlkValue').find('aValue').text
    results.addFloat('ECF',ECF,level=2)
    ImagePlaneEfficiency = detres.find('gPlaneEff').find('cBlkValue').find('aValue').text
    results.addFloat('Plane efficiency',ImagePlaneEfficiency,level=2)
    BlockTimingOffset = detres.find('hTimeAlignment').find('cBlkValue').find('aValue').text
    results.addFloat('BlockTimingOffset',BlockTimingOffset,level=2)
    BlockTimingWidth = detres.find('iTAFWHM').find('cBlkValue').find('aValue').text
    results.addFloat('BlockTimingWidth',BlockTimingWidth,level=2)
    TimeAlignmentResidual =  detres.find('lTAResidual').find('cBlkValue').find('aValue').text
    results.addFloat('Time alignment residual',TimeAlignmentResidual,level=2)

