
import tempfile as tmp
import sys
import subprocess

def browse(files=[], browser='Firefox', colormap=None):
    if not files:
        import glob
        filepattern = '*.rwa'
        if not glob.glob(filepattern):
            filepattern = '*/*.rwa'
            if not glob.glob(filepattern):
                print('cannot find any matching rwa file')
                return
        files = [filepattern]

    script = tmp.NamedTemporaryFile('w', suffix='.py', encoding='utf-8', delete=False)
    source = """\
#!/usr/bin/env python3

from tramway.analyzer import *
from selenium import webdriver

a = RWAnalyzer()
a.spt_data.from_rwa_files(['{}'])
a.env.script = '{}'
{}a.browser.show_maps(webdriver=webdriver.{})
""".format("', '".join(files), script.name,
        '' if colormap is None else "a.browser.colormap = '{}'\n".format(colormap),
        browser)
    script.write(source)
    script.flush()
    p = subprocess.Popen([sys.executable, script.name],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    try:
        ret = p.communicate()
    except KeyboardInterrupt:
        ret = p.communicate()
    script.close()
    def tostr(s):
        if isinstance(s, bytes):
            s = s.decode('utf8')
        return s
    ret = [ tostr(r) for r in ret ]
    return [ r for r in ret if r ]


def main():
    import argparse
    parser = argparse.ArgumentParser(prog='tramway-browse',
        description='Browse TRamWAy-generated .rwa files')
    parser.add_argument('files', nargs='*', help='for example: *.rwa or */*.rwa')
    parser.add_argument('--browser', default='Firefox', choices=['Firefox','Chrome','Edge','Ie','Opera','Safari','WebKitGTK'])
    parser.add_argument('--colormap', help="Matplotlib colormap name")
    [ print(ret) for ret in browse(**parser.parse_args().__dict__) ]

if __name__ == '__main__':
    main()

