# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from __python__ import bound_methods, hash_literals

from elementmaker import E
from gettext import gettext as _

from book_list.globals import get_session_data
from dom import add_extra_css, build_rule, element, unique_id
from read_book.prefs.utils import create_button_box
from read_book.globals import runtime
from session import defaults

CONTAINER = unique_id('reader-page-layout')
MARGINS = unique_id('reader-page-margins')
READ_MODE = unique_id('read-mode')
FS_MODE = unique_id('fs-mode')
COLS = unique_id('cols-per-screen')
TEXT_AREA = unique_id('text-area')

add_extra_css(def():
    sel = '#' + MARGINS
    style = build_rule(sel, margin_left='1rem', margin_top='-1ex')
    style += build_rule('#{} td'.format(CONTAINER), padding='1ex')
    return style
)

def restore_defaults():
    container = document.getElementById(CONTAINER)
    for which in 'top bottom left right'.split(' '):
        container.querySelector('input[name={}]'.format(which)).value = str(defaults['margin_' + which])
    for name in 'paged flow'.split(' '):
        container.querySelector(f'#{READ_MODE} input[data-name={name}]').checked = defaults.read_mode is name
    if not runtime.is_standalone_viewer:
        container.querySelector(f'#{FS_MODE} input[value={defaults.fullscreen_when_opening}]').checked = True
    for name in 'portrait landscape'.split(' '):
        container.querySelector('input[name={}]'.format(name)).value = str(defaults.columns_per_screen[name])
    for which in 'width height'.split(' '):
        container.querySelector('input[name={}]'.format(which)).value = str(defaults['max_text_' + which])
    container.querySelector('input[name=cover_preserve_aspect_ratio]').checked = defaults.cover_preserve_aspect_ratio


def create_layout_panel(container, apply_func, cancel_func):
    container.appendChild(E.div(id=CONTAINER))
    container = container.lastChild
    sd = get_session_data()
    container.appendChild(E.p(_('Change the page margins (in pixels) below'), style='margin:1ex 1rem; padding: 1ex 0'))
    container.appendChild(E.table(id=MARGINS))
    labels = {'top':_('Top:'), 'bottom':_('Bottom:'), 'left':_('Left:'), 'right':_('Right:')}

    def item(which, tr):
        tr.appendChild(E.td(labels[which]))
        tr.appendChild(E.td(E.input(type='number', max='9999', min='0', step='1', name=which, value=str(sd.get('margin_' + which)))))

    container.lastChild.appendChild(E.tr())
    item('left', container.lastChild.lastChild)
    item('right', container.lastChild.lastChild)
    container.lastChild.appendChild(E.tr())
    item('top', container.lastChild.lastChild)
    item('bottom', container.lastChild.lastChild)

    def sec(text):
        container.appendChild(E.div(text, style='margin: 2ex 1rem; padding-top:2ex; border-top: solid 1px; max-width: 50em'))

    sec(_('Choose the page layout mode. In paged mode, the text is split up into individual pages, as in a paper book. In flow mode'
            ' text is presented as one long scrolling page, as in web browsers.'))
    container.appendChild(E.div(id=READ_MODE, style='margin: 1ex 2rem; display: flex;'))
    rm = sd.get('read_mode')
    rm = 'flow' if rm is 'flow' else 'paged'
    def rb(name, text):
        d = container.lastChild
        d.appendChild(E.label(E.input(type='radio', name='page-layout-mode', data_name=name, checked=rm is name), text))
    rb('paged', _('Paged mode'))
    container.lastChild.appendChild(E.span('\xa0', style='width:3em'))
    rb('flow', _('Flow mode'))

    sec(_('In paged mode, control the number of pages per screen. A setting of zero means the number of pages is'
          ' set based on the screen size.'))
    cps = sd.get('columns_per_screen')
    container.appendChild(E.table(style='margin: 1ex 1rem', id=COLS,
        E.tr(
            E.td(_('Portrait:')), E.td(E.input(type='number', name='portrait',   min='0', step='1', max='20', value=str(cps.portrait))),
            E.td(_('Landscape:')), E.td(E.input(type='number', name='landscape', min='0', step='1', max='20', value=str(cps.landscape))),
    )))

    sec(_('Change the maximum screen area (in pixels) used to display text.'
          ' A value of zero means that all available screen area is used.'
          ' Current window width is {0} and height is {1} pixels.'
    ).format(window.innerWidth, window.innerHeight))
    container.appendChild(E.table(style='margin: 1ex 1rem', id=TEXT_AREA,
        E.tr(
            E.td(_('Width:')), E.td(E.input(type='number', name='width',   min='0', step='10', max='99999', value=str(sd.get('max_text_width')))),
            E.td(_('Height:')), E.td(E.input(type='number', name='height', min='0', step='10', max='99999', value=str(sd.get('max_text_height')))),
    )))

    sec(_('Miscellaneous'))
    container.appendChild(E.div(style='margin: 1ex 2rem; display: flex;',
        E.label(E.input(type='checkbox', name='cover_preserve_aspect_ratio', checked=sd.get('cover_preserve_aspect_ratio')), _('Preserve cover aspect ratio'))))
    if not runtime.is_standalone_viewer:
        name = 'fullscreen_when_opening'
        val = sd.get(name)
        if 'auto always never'.split(' ').indexOf(val or '') < 0:
            val = defaults.fullscreen_when_opening
        container.appendChild(E.div(
            E.div(style='margin: 1ex 2rem', id=FS_MODE,
                _('When opening a book enter fullscreen:'), ' ',
                E.label(E.input(type='radio', name=name, value='auto', checked=val is 'auto'), _('Auto')),
                '\xa0',
                E.label(E.input(type='radio', name=name, value='always', checked=val is 'always'), _('Always')),
                '\xa0',
                E.label(E.input(type='radio', name=name, value='never', checked=val is 'never'), _('Never')),
            )
        ))

    container.appendChild(E.div(style='margin: 1rem', create_button_box(restore_defaults, apply_func, cancel_func)))


develop = create_layout_panel


def commit_layout(onchange, container):
    was_changed = False
    sd = get_session_data()
    for which in 'top bottom left right'.split(' '):
        i = element(MARGINS, '[name={}]'.format(which))
        try:
            val = int(i.value)
        except:
            continue
        if val is not sd.get('margin_' + which):
            was_changed = True
            sd.set('margin_' + which, val)
    rm = sd.get('read_mode')
    rm = 'flow' if rm is 'flow' else 'paged'
    crm = 'paged' if element(READ_MODE, 'input').checked else 'flow'
    if rm is not crm:
        was_changed = True
        sd.set('read_mode', crm)
    if not runtime.is_standalone_viewer:
        fs = sd.get('fullscreen_when_opening')
        cfs = document.querySelector(f'#{FS_MODE} input[name="fullscreen_when_opening"]:checked').value
        if cfs is not fs:
            was_changed = True
            sd.set('fullscreen_when_opening', cfs)
    cps = sd.get('columns_per_screen')
    cps = {'portrait': cps.portrait, 'landscape': cps.landscape}
    for which in ('portrait', 'landscape'):
        inp = element(COLS, 'input[name={}]'.format(which))
        try:
            val = int(inp.value)
        except:
            continue
        if cps[which] is not val:
            cps[which] = val
            sd.set('columns_per_screen', cps)
            was_changed = True
    for which in ('width', 'height'):
        try:
            val = int(element(TEXT_AREA, 'input[name={}]'.format(which)).value)
        except:
            continue
        if val is not sd.get('max_text_' + which):
            was_changed = True
            sd.set('max_text_' + which, val)

    cover_preserve_aspect_ratio = element(CONTAINER, 'input[name=cover_preserve_aspect_ratio]').checked
    if cover_preserve_aspect_ratio is not sd.get('cover_preserve_aspect_ratio'):
        was_changed = True
        sd.set('cover_preserve_aspect_ratio', cover_preserve_aspect_ratio)

    if was_changed:
        onchange()
