#!/usr/bin/env python3
"""
Create HTML report from QC analysis results

AUTHORS
----
Mike Tyszka, Ph.D., Caltech Brain Imaging Center

DATES
----
2013-09-25 JMT From scratch
2013-10-23 JMT Add com external call
2013-10-24 JMT Move stats calcs to new stats.py
2019-05-28 JMT Recode as a nipype interface class
2019-05-29 JMT Expand to multiple pages

MIT License

Copyright (c) 2019 Mike Tyszka

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import os
import json
import shutil
import datetime as dt

from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import (SimpleDocTemplate,
                                Paragraph,
                                Spacer,
                                Image,
                                Table,
                                TableStyle,
                                PageBreak)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch


class ReportPDF:

    def __init__(self, fnames, meta, metrics):

        self._fnames = fnames
        self._meta = meta
        self._metrics = metrics
        self._tmp_report_pdf = os.path.join(fnames['WorkDir'], 'report.pdf')

        # Contents - list of flowables to be built into a document
        self._contents = []

        # Add a justified paragraph style
        self._pstyles = getSampleStyleSheet()
        self._pstyles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))

        self._init_pdf()
        self._add_summary()
        self._add_roi_timeseries()
        self._add_motion_timeseries()
        self._add_sections()
        self._add_demeaned_ts()

        self._doc.build(self._contents)
        self._save_report()

    def _init_pdf(self):

        # Create a new PDF document
        self._doc = SimpleDocTemplate(self._tmp_report_pdf,
                                      pagesize=letter,
                                      rightMargin=0.5 * inch,
                                      leftMargin=0.5 * inch,
                                      topMargin=0.5 * inch,
                                      bottomMargin=0.5 * inch)

    def _add_summary(self):

        ptext = '<font size=24>CBIC Quality Control Report</font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.5 * inch))

        timestamp = dt.datetime.now().strftime('%Y-%m-%d at %H:%M:%S')
        ptext = '<font size=12>Generated by CBICQC on {}</font>'.format(timestamp)
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        #
        # Session information
        #

        ptext = '<font size=14><b>Session Information</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        demo = [['Subject', self._meta['Subject']],
                ['Session', self._meta['Session']],
                ['Scan Time', self._meta['AcquisitionTime']],
                ['Software Version', self._meta['SoftwareVersions']],
                ['Pulse Sequence', self._meta['SequenceName']],
                ['Coil Name', self._meta['ReceiveCoilName']],
                ['', '']
                ]

        image = [['Repetition Time', '{} ms'.format(self._meta['RepetitionTime'] * 1e3)],
                 ['Echo Time', '{} ms'.format(self._meta['EchoTime'] * 1e3)],
                 ['Voxel Size', '{} mm'.format(self._meta['VoxelSize'])],
                 ['Matrix Size', self._meta['MatrixSize']],
                 ['EPI Echo Spacing', '{0:.0f} us'.format(self._meta['EffectiveEchoSpacing'] * 1e6)],
                 ['RO Bandwidth', '{} Hz/pix'.format(self._meta['PixelBandwidth'])],
                 ['PE Bandwidth', '{} Hz/pix'.format(self._meta['BandwidthPerPixelPhaseEncode'])]]

        demo_table = Table(demo, hAlign='LEFT')
        image_table = Table(image, hAlign='LEFT')

        self._contents.append(Table([[demo_table, image_table]]))
        self._contents.append(Spacer(1, 0.25 * inch))

        #
        # QC metrics
        #

        ptext = '<font size=14><b>Quality Metrics</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        signal_metrics = [['Mean Signal', '{:.1f}'.format(self._metrics['SignalMean'])],
                          ['SNR', '{:.1f}'.format(self._metrics['SNR'])],
                          ['SFNR', '{:.1f}'.format(self._metrics['SFNR'])],
                          ['SArtR', '{:.1f}'.format(self._metrics['SArtR'])],
                          ['Drift', '{:.3f} %/TR'.format(self._metrics['Drift'])],
                          ['Warmup Amplitude', '{:.3f} %'.format(self._metrics['WarmupAmp'])],
                          ['Warmup Time Constant', '{:.1f} TRs'.format(self._metrics['WarmupTime'])]
                          ]

        ptext = '<font size=11><b>Main Signal</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        signal_table = Table(signal_metrics, hAlign='LEFT')
        self._contents.append(signal_table)
        self._contents.append(Spacer(1, 0.25 * inch))

        noise_metrics = [['Noise Sigma', '{:.1f}'.format(self._metrics['NoiseSigma'])],
                         ['Noise Floor', '{:.1f}'.format(self._metrics['NoiseFloor'])],
                         ['Signal Spikes', '{}'.format(self._metrics['SignalSpikes'])],
                         ['Nyquist Ghost Spikes', '{}'.format(self._metrics['NyquistSpikes'])],
                         ['Air Spikes', '{}'.format(self._metrics['AirSpikes'])],
                         ]

        ptext = '<font size=11><b>Noise and Spiking</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        noise_table = Table(noise_metrics, hAlign='LEFT')
        self._contents.append(noise_table)
        self._contents.append(Spacer(1, 0.25 * inch))

    def _add_roi_timeseries(self):

        # Page break
        self._contents.append(PageBreak())

        #
        # ROI Spatial Mean Timeseries
        #

        ptext = '<font size=14><b>ROI Spatial Mean Timeseries</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        ptext = """
        <font size=11>
        These three graphs show the spatial mean signal intensity within the main signal, Nyquist ghost and air
        space regions of interest (ROIs). The blue line is the raw spatial mean intensity and the orange line
        has been detrended with an exponential + linear model. 
        </font>
        """
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        roi_ts_img = Image(self._fnames['ROITimeseries'], 7.0 * inch, 3.5 * inch, hAlign='LEFT')
        self._contents.append(roi_ts_img)

        self._contents.append(Spacer(1, 0.5 * inch))

        #
        # ROI Spatial Mean Power Spectrum
        #

        ptext = '<font size=14><b>ROI Power Spectra</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        ptext = """
        <font size=11>
        Power spectrum of the spatial mean signal in each ROI. The dB scale is relative to maximum spectral power.
        </font>
        """
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        roi_ps_img = Image(self._fnames['ROIPowerspec'], 7.0 * inch, 3.5 * inch, hAlign='LEFT')
        self._contents.append(roi_ps_img)

        self._contents.append(Spacer(1, 0.5 * inch))


    def _add_motion_timeseries(self):

        # Page break
        self._contents.append(PageBreak())

        #
        # Motion Parameter Timeseries
        #

        ptext = '<font size=14><b>Motion Parameter Timeseries</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        # Main signal QC specific text
        ptext = """
        <font size=11>
        Displacement and rotation parameter timecourses required
        to register the center of mass at a given time to the center of mass of the first image. 
        </font>
        """
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        mo_ts_img = Image(self._fnames['MoparTimeseries'], 7.0 * inch, 3.5 * inch, hAlign='LEFT')
        self._contents.append(mo_ts_img)

        self._contents.append(Spacer(1, 0.5 * inch))

        #
        # Motion Power Spectra
        #

        ptext = '<font size=14><b>Motion Power Spectra</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        ptext = """
        <font size=11>
        Power spectrum of the absolute displacement and total rotation timecourses.
        The dB scale is relative to maximum spectral power.
        </font>
        """
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        mo_ts_img = Image(self._fnames['MoparPowerspec'], 7.0 * inch, 3.5 * inch, hAlign='LEFT')
        self._contents.append(mo_ts_img)

        self._contents.append(Spacer(1, 0.5 * inch))

    def _add_sections(self):

        # Page break
        self._contents.append(PageBreak())

        ptext = '<font size=14><b>Image Sections</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        self._add_section('Temporal Mean', self._fnames['TMeanMontage'])
        self._add_section('Temporal Standard Deviation', self._fnames['TSDMontage'])
        self._add_section('Regions of Interest', self._fnames['ROIsMontage'])

    def _add_section(self, title, img_fname):

        ptext = '<font size=11><b>{}</b></font>'.format(title)
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        tmean_montage_img = Image(img_fname, 7.0 * inch, 2.4 * inch, hAlign='LEFT')

        self._contents.append(tmean_montage_img)
        self._contents.append(Spacer(1, 0.25 * inch))

    def _add_demeaned_ts(self):

        # Page break
        self._contents.append(PageBreak())

        ptext = '<font size=14><b>Demeaned Signal</b></font>'
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.25 * inch))

        ptext = """
        <font size=11>
        Demeaned signal timecourses for a subsample of voxels from each ROI.
        </font>
        """
        self._contents.append(Paragraph(ptext, self._pstyles['Justify']))
        self._contents.append(Spacer(1, 0.1 * inch))

        residuals_img = Image(self._fnames['ROIDemeanedTS'], 7.0 * inch, 9.0 * inch, hAlign='LEFT')
        self._contents.append(residuals_img)

    def _save_report(self):

        # Copy report PDF to derivatives
        shutil.copyfile(self._tmp_report_pdf, self._fnames['ReportPDF'])

        # Save metrics in derivatives as JSON file
        with open(self._fnames['ReportJSON'], 'w') as fd:
            json.dump(self._metrics, fd, sort_keys=True, indent=4)


