#!/usr/bin/env fslpython
#
# pnm_stage1
#
# Mark Jenkinson, FMRIB Image Analysis Group
# (re-written in Python by Paul McCarthy)
#
#   Part of FSL - FMRIB's Software Library
#   http://www.fmrib.ox.ac.uk/fsl
#   fsl@fmrib.ox.ac.uk
#
#   Developed at FMRIB (Oxford Centre for Functional Magnetic Resonance
#   Imaging of the Brain), Department of Clinical Neurology, Oxford
#   University, Oxford, UK
#
#
#   LICENCE
#
#   FMRIB Software Library, Release 6.0 (c) 2018, The University of
#   Oxford (the "Software")
#
#   The Software remains the property of the Oxford University Innovation
#   ("the University").
#
#   The Software is distributed "AS IS" under this Licence solely for
#   non-commercial use in the hope that it will be useful, but in order
#   that the University as a charitable foundation protects its assets for
#   the benefit of its educational and research purposes, the University
#   makes clear that no condition is made or to be implied, nor is any
#   warranty given or to be implied, as to the accuracy of the Software,
#   or that it will be suitable for any particular purpose or for use
#   under any specific conditions. Furthermore, the University disclaims
#   all responsibility for the use which is made of the Software. It
#   further disclaims any liability for the outcomes arising from using
#   the Software.
#
#   The Licensee agrees to indemnify the University and hold the
#   University harmless from and against any and all claims, damages and
#   liabilities asserted by third parties (including claims for
#   negligence) which arise directly or indirectly from the use of the
#   Software or the sale of any products based on the Software.
#
#   No part of the Software may be reproduced, modified, transmitted or
#   transferred in any form or by any means, electronic or mechanical,
#   without the express permission of the University. The permission of
#   the University is not required if the said reproduction, modification,
#   transmission or transference is done without financial return, the
#   conditions of this Licence are imposed upon the receiver of the
#   product, and all original and amended source code is included in any
#   transmitted product. You may be held legally responsible for any
#   copyright infringement that is caused or encouraged by your failure to
#   abide by these terms and conditions.
#
#   You are not permitted under this Licence to use this Software
#   commercially. Use for which any financial return is received shall be
#   defined as commercial use, and includes (1) integration of all or part
#   of the source code or the Software into a product for sale or license
#   by or on behalf of Licensee to third parties or (2) use of the
#   Software or any derivative of it for research with the final aim of
#   developing software products for sale or license to a third party or
#   (3) use of the Software or any derivative of it for research with the
#   final aim of developing non-software products for sale or license to a
#   third party, or (4) use of the Software to provide any service to an
#   external organisation for which payment is received. If you are
#   interested in using the Software commercially, please contact Oxford
#   University Innovation ("OUI"), the technology transfer company of the
#   University, to negotiate a licence. Contact details are:
#   fsl@innovation.ox.ac.uk quoting Reference Project 9564, FSL.


import                    contextlib
import http.server     as http
import os.path         as op
import                    os
import multiprocessing as mp
import                    shutil
import                    sys
import                    time
import                    webbrowser

from fsl.utils.run import run, runfsl



def usage():
    print('Usage: pnm_stage1 [popp options]')
    print('   Runs popp (see options below) and then creates necessary scripts')
    print('     to run manual webpage editing (and second stage if GUI was used)')
    print(runfsl('popp', stderr=True, exitcode=True)[1])


def find_output_basename(argv):
    """Finds the output basename in the command-line arguments that are
    destined for popp.
    """
    for i, arg in enumerate(argv):
        if arg == '-o':
            basename = argv[i + 1]
            break
        elif arg.startswith('--out'):
            basename = arg.split('=')[1]
            break
    else:
        print('Cannot find output basename!')
        raise SystemExit(1)

    return op.abspath(basename)


def generate_pnm_stage2(cpwd, basename, argv):
    """Creates the pnm_stage2 script. """
    argv       = ' '.join(argv)
    stage2     = f'{basename}_pnm_stage2'
    stage3     = f'{basename}_pnm_stage3'
    havestage3 = op.exists(stage3)
    with open(f'{basename}_pnm_stage2', 'wt') as f:
        f.write('#!/usr/bin/env bash\n')
        f.write(f'cd {cpwd}\n')
        f.write(f'obase={basename}\n')
        f.write( 'export obase\n')
        f.write(f'if [ $# -gt 0 ] ; then $FSLDIR/bin/popp {argv} $@ ; fi\n')
        if havestage3:
            f.write(f'{stage3}\n')
    os.chmod(stage2, 0o755)
    if havestage3:
        os.chmod(stage3, 0o755)


def create_html_report(basename):
    """Create the pnm HTML report, used for manually verifying / identifying
    peaks.
    """

    # Use relative paths in HTML/js
    if op.isdir(basename):
        basedir = basename
        urlbase = ''
    else:
        basedir = op.dirname( basename)
        urlbase = op.basename(basename)

    # copy webpage template and replace FSLDIR
    # stubs and output basename data file
    fsldir  = os.environ['FSLDIR']
    tmpldir = f'{fsldir}/data/feat5/pnm_templates/'
    repls   = [('label-div.html',       f'{urlbase}_pnm2.html'),
               ('pnm_lower_frame.html', f'{urlbase}_pnm3.html'),
               ('./pnm_stage2',         f'{urlbase}_pnm_stage2'),
               ('PNMSTAGE2',            f'{urlbase}_pnm_stage2'),
               ('PNMDATA.js',           f'{urlbase}_pnm.js'),
               ('FSLDIR',               fsldir)]

    def create_page(src, dest):
        with open(src, 'rt') as f:
            content = f.read()

        for find, replace in repls:
            content = content.replace(find, replace)

        with open(dest, 'wt') as f:
            f.write(content)

    create_page(f'{tmpldir}/pnm_main_frame.html',  f'{basename}_pnm1.html')
    create_page(f'{tmpldir}/label-div.html',       f'{basename}_pnm2.html')
    create_page(f'{tmpldir}/pnm_lower_frame.html', f'{basename}_pnm3.html')
    shutil.copy(f'{tmpldir}/dygraph-canvas.js',    basedir)
    shutil.copy(f'{tmpldir}/dygraph.js',           basedir)
    shutil.copy(f'{tmpldir}/rgbcolor.js',          basedir)
    shutil.copy(f'{tmpldir}/strftime-min.js',      basedir)




@contextlib.contextmanager
def indir(dir):
    """Context manager which temporarily changes into dir."""
    prevdir = os.getcwd()
    os.chdir(dir)
    try:
        yield
    finally:
        os.chdir(prevdir)


class HTTPServer(mp.Process):
    """Simple HTTP server which serves files from a specified directory.

    Intended to be used via the :func:`server` context manager function.
    """
    def __init__(self, rootdir):
        mp.Process.__init__(self)
        self.daemon   = True
        self.rootdir  = rootdir
        self.portval  = mp.Value('i', -1)
        self.startup  = mp.Event()
        self.shutdown = mp.Event()

    def stop(self):
        self.shutdown.set()

    @property
    def port(self):
        return self.portval.value

    def run(self):
        # Suppress log messages
        handler             = http.SimpleHTTPRequestHandler
        handler.log_message = lambda *a: None
        server              = http.HTTPServer(('', 0), handler)

        # store port number, notify startup
        self.portval.value = server.server_address[1]
        self.startup.set()

        with indir(self.rootdir):
            while not self.shutdown.is_set():
                server.handle_request()
            server.shutdown()


@contextlib.contextmanager
def server(rootdir=None):
    """Start a HTTPServer on a separate thread to serve files from
    rootdir (defaults to the current working directory), then shut it down
    afterwards.
    """
    if rootdir is None:
        rootdir = os.getcwd()
    srv = HTTPServer(rootdir)
    srv.start()
    # wait until server has started
    srv.startup.wait()
    srv.url = 'http://localhost:{}'.format(srv.port)
    try:
        yield srv
    finally:
        srv.stop()


def main():
    cpwd = os.getcwd()
    argv = sys.argv[1:]
    if len(argv) == 0:
        usage()
        return 1

    # extract output basename from the passed popp arguments
    basename = find_output_basename(argv)

    # run popp
    poppcmd = ['popp'] + argv
    print(' '.join(poppcmd))
    runfsl(poppcmd)

    # # make the next script - if GUI
    # # is run then this also includes
    # # the pnm_evs call
    generate_pnm_stage2(cpwd, basename, argv)

    create_html_report(basename)

    # Open the PNM web report in a web browser.
    # Use a web server to avoid cross-origin
    # request errors. The web server can be shut
    # down immediately, as all files will be
    # loaded as soon as the main report page is
    # opened.
    report     = f'{basename}_pnm1.html'
    reportdir  = op.dirname( report)
    reportfile = op.basename(report)
    with server(reportdir) as srv:
        url = f'{srv.url}/{reportfile}'
        webbrowser.open_new_tab(url)
        time.sleep(5)
        srv.shutdown.set()


if __name__ == '__main__':
    sys.exit(main())
