from __future__ import division
import math

from . import resources
from .screens import get_path

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

MACROS = dict(
    IFO = '$(IFO)',
    SYSTEM = '$(SYSTEM)',
    SYSTEM_PATH = '$(SYSTEM_PATH)',
    )


def gen_macro_str(**kwargs):
    macros = MACROS.copy()
    if kwargs:
        macros.update(kwargs)
    return ','.join(['{}={}'.format(k, v) for k, v in macros.items()])


def gen_composite(**kwargs):
    path = get_path(kwargs['screen'])
    kwargs['macros'] = gen_macro_str(**kwargs.get('macros', {}))
    return '''
composite {{
        object {{
                x={x}
                y={y}
                width={width}
                height={height}
        }}
        "composite name"=""
        "composite file"="{path}; {macros}"
}}
'''.format(path=path, **kwargs)

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

def write_screen_main(f, system):
    displays = system.related_displays + [('OVERVIEW',
                                           '$(USERAPPS)/sys/$(ifo)/medm/GUARD_OVERVIEW.adl',
                                           ''
                                           )]
    with open(get_path('GRD_MAIN.adl')) as fs:
        f.write(fs.read())
    f.write(resources.related_display_menu(displays,
                                           x=414,
                                           y=107,
                                           width=90,
                                           height=20,
                                           ))

def write_screen_compact(f):
    with open(get_path('GRD_COMPACT.adl')) as fs:
        f.write(fs.read())

def write_screen_minis(f):
    f.write(resources.header(bclr=14, height=400, width=400))
    y = 10
    for screen in ['GRD_NANO.adl', 'GRD_MICRO.adl', 'GRD_MINI.adl',
                   'GRD_MINI_USERMSG.adl', 'GRD_MINI_REQUEST_USERMSG.adl']: #, 'STATUSBAR']:
        f.write(gen_composite(screen=screen,
                              x=10, y=y, width=10, height=10))
        y += 70

def write_screen_states(f, system):
    states = system.states + ['NONE']
    nstates = len(states)

    margin = 10
    title_height = 18
    state_width = 305
    state_height = 25
    legend_height = 50

    # determine nice rectangle of state buttons
    sbar = state_width / float(state_height)
    rows = nstates
    cols = 1
    while rows > sbar*cols and nstates > 24:
        cols += 1
        rows = int(math.ceil(nstates/cols))
    def rc(i):
        col = int(math.floor(float(i)/rows))
        return i-col*rows, col

    offset = 84
    button_top = title_height + margin + offset
    width = margin + cols * state_width
    height = button_top + state_height*rows + margin
    if cols == 1:
        height += legend_height

    f.write(resources.header(height=height, width=width))
    f.write(resources.background(height=height, width=width))
    f.write(resources.title(x=48))

    f.write(gen_composite(screen='GRD_STATES_HEAD.adl',
                          x=10, y=title_height+margin, width=300, height=200))

    for i, state in enumerate(states):
        r,c = rc(i)
        x = margin + c*state_width
        y = button_top + r*state_height
        if state == 'NONE':
            index = -1
            is_goto = False
            is_request = True
        else:
            index = system.index(state)
            is_goto = system.is_goto(state)
            is_request = system.is_request(state)
        f.write(resources.state_request_button(x=x, y=y,
                                               state=state, index=index,
                                               is_request=is_request,
                                               is_goto=is_goto,
                                               ))
        f.write(gen_composite(screen='GRD_STATES_TARGET.adl',
                              macros={'STATE_N': index},
                              x=x+270, y=y,
                              width=25, height=25))

    lx = 17
    ly = button_top+rows*state_height+8
    if cols > 1:
        lx = margin + state_width + 7
        ly = title_height + margin + 28
    f.write(gen_composite(screen='GRD_STATES_LEGEND.adl',
                          x=lx, y=ly,
                          width=315, height=18))

def write_screen_spm(f):
    with open(get_path('GRD_SPM.adl')) as fs:
        f.write(fs.read())

def write_screen_usermsg(f):
    with open(get_path('GRD_USERMSG.adl')) as fs:
        f.write(fs.read())

def write_composite_status(f, x=0, y=0):
    f.write(gen_composite(screen='GRD_STATUSBAR.adl',
                          x=x, y=y, width=10, height=10))
