from __future__ import division, print_function
import sys
import time
import argparse
import tempfile
import subprocess

from .. import cli
from .. import const
from ..system import GuardSystem
from .screens import get_path
from . import resources
from . import gen

# FIXME: set displayFont properly
DISPLAY_FONT = '-misc-fixed-medium-r-normal--8-60-100-100-c-50-iso8859-1'

##################################################

PROG = 'guardmedm'
description = '''Advanced LIGO Guardian MEDM control screen.'''
epilog = """
Environment variables:
  IFO                       IFO designator (required)
  USERAPPS_DIR              LIGO "userapps" root path ('/opt/rtcds/userapps/release')
  GUARD_MODULE_PATH         Override default userapps system module search path
"""

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    prog=PROG,
    description=description,
    epilog=epilog,
    prefix_chars='-+',
    )

cli.parser_add_version(parser)
cli.parser_add_system(parser)

tgroup = parser.add_mutually_exclusive_group()
tgroup.add_argument('--main', dest='stype', action='store_const', const='main',
                    help="main control screen (default)")
tgroup.add_argument('--compact', dest='stype', action='store_const', const='compact',
                    help="compact control screen")
tgroup.add_argument('--states', dest='stype', action='store_const', const='states',
                    help="state request screen")
tgroup.add_argument('--minis', dest='stype', action='store_const', const='minis',
                    help="mini state panels")
tgroup.add_argument('--status', dest='stype', action='store_const', const='status',
                    help="status screen (multiple nodes may be specified)")
tgroup.add_argument('--spm', dest='stype', action='store_const', const='spm',
                    help="set point monitor")
tgroup.add_argument('--usermsg', dest='stype', action='store_const', const='usermsg',
                    help="notification messages")
parser.set_defaults(stype='main')

pgroup = parser.add_mutually_exclusive_group()
pgroup.add_argument('--print', action='store_true', dest='sprint',
                    help="print screen .adl to stdout")
pgroup.add_argument('--paths', action='store_true',
                    help="print built-in screen paths and exit")

parser.add_argument('+attach', action='store_false',
                    help="don't attach to running MEDM")

##################################################

def main():
    """Exec Guardian MEDM screen for system.

    """
    args = parser.parse_args()

    if args.paths:
        for screen in ['GRD_MAIN.adl', 'GRD_COMPACT.adl',
                       'GRD_MINI_REQUEST_USERMSG.adl',
                       'GRD_MINI_USERMSG.adl',
                       'GRD_MINI.adl', 'GRD_MICRO.adl', 'GRD_NANO.adl',
                       'GRD_STATUSBAR.adl',
                       'GRD_SPM.adl', 'GRD_USERMSG.adl'
                      ]:
            print(get_path(screen))
        sys.exit()

    if not const.IFO:
        sys.exit("Must specify IFO environment variable.")

    if not args.system:
        parser.error("must specify system or --paths.")

    cmd = ['medm', 'medm', '-x', '-noMsg',
           '-dg', '+0+0',
           '-displayFont', DISPLAY_FONT,
          ]

    if args.attach:
        cmd += ['-attach']

    ############################################################

    if args.stype == 'status':
        prefix = '{}:GRD.STATUS.'.format(const.IFO)
        cmd += ['-macro', 'IFO={}'.format(const.IFO)]
        screen = get_path('GRD_STATUSBAR.adl')
        sheight = 29
        border = 0
        height = border + len(args.system) * sheight + border + 3
        width = 856
        x = border
        y = border
        with tempfile.NamedTemporaryFile('tw+', prefix=prefix, suffix='.adl') as f:
            f.write(resources.header(bclr=14, height=height, width=width))
            for s in args.system:
                try:
                    name = GuardSystem(s).name
                except:
                    name = s
                f.write('''
composite {{
	object {{
		x={x}
		y={y}
		width=10
		height=10
	}}
	"composite name"=""
        "composite file"="{path}; IFO=$(IFO), SYSTEM={system}"
}}
'''.format(x=x, y=y, path=screen, system=name))
                y += sheight
            f.seek(0)

            if args.sprint:
                sys.stdout.write(f.read())
            else:
                cmd += [f.name]
                print(' '.join(cmd[1:]), file=sys.stderr)
                try:
                    subprocess.run(cmd)
                    time.sleep(.5)
                except KeyboardInterrupt:
                    pass
        sys.exit()

    else:
        system = cli.init_system(args)

    ############################################################

    cmd += ['-macro',
            gen.gen_macro_str(
                IFO=const.IFO,
                SYSTEM=system.name,
                SYSTEM_PATH=system.path,
            )
    ]

    prefix = const.CAS_PREFIX_FMT.format(IFO=const.IFO, SYSTEM=system.name).strip('_')
    wargs = ()

    if args.stype == 'main':
        prefix += '.MAIN.'
        write_func = gen.write_screen_main
        wargs = (system,)

    elif args.stype == 'compact':
        prefix += '.COMPACT.'
        write_func = gen.write_screen_compact

    elif args.stype == 'minis':
        prefix += '.MINIS.'
        write_func = gen.write_screen_minis

    elif args.stype == 'states':
        prefix += '.STATES.'
        write_func = gen.write_screen_states
        system.load()
        wargs = (system,)

    elif args.stype == 'spm':
        prefix += '.SPM.'
        write_func = gen.write_screen_spm

    elif args.stype == 'usermsg':
        prefix += '.USERMSG.'
        write_func = gen.write_screen_usermsg

    ############################################################

    with tempfile.NamedTemporaryFile('tw+', prefix=prefix, suffix='.adl',) as f:
        write_func(f, *wargs)
        f.seek(0)
        if args.sprint:
            sys.stdout.write(f.read())
        else:
            cmd += [f.name]
            print(' '.join(cmd[1:]), file=sys.stderr)
            try:
                subprocess.run(cmd)
                time.sleep(.5)
            except KeyboardInterrupt:
                pass



if __name__ == '__main__':
    main()
