#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: brython (http://brython.info) (like python3)
#
# Imports =====================================================================
from os.path import join

from browser import document

from .overlay_controller import BlackOverlay

# virtual filesystem / modules provided by REST API
from virtual_fs import settings


# Functions & classes =========================================================
class OutputPicker(object):
    """
    This class controlls the interface for picking the output from the MRC /
    MARC / DC conversions.

    It also allows the user to download all converted datasets as files.
    """
    el = document["output_picker"]

    overlay = BlackOverlay()

    mrc_out_el = document["mrc_output"]
    oai_out_el = document["marc_oai_output"]
    dc_out_el = document["dublin_core_output"]

    values = None
    filename = "fn"

    @classmethod
    def set(cls, values):
        """
        Set the elements from the data obtained from REST API.

        Args:
            values (dict): Dict with ``mrc``, ``oai``, ``dc`` and ``fn`` keys.
        """
        cls.mrc_out_el.text = values.get("mrc", "")
        cls.oai_out_el.text = values.get("oai", "")
        cls.dc_out_el.text = values.get("dc", "")
        cls.filename = values.get("fn", "fn")

        cls.values = values

    @classmethod
    def show(cls, values=None):
        """
        Show the interface for picking / downloading the datasets.
        """
        if values:
            cls.set(values)

        cls.el.style.display = "block"

        cls.overlay.show()
        cls.overlay.el.bind("click", lambda x: cls.hide())

    @classmethod
    def hide(cls):
        """
        Hide interface.
        """
        cls.overlay.hide()
        cls.el.style.display = "none"

    @classmethod
    def bind_download_buttons(cls):
        """
        Bind buttons to callbacks.
        """
        def on_click(ev):
            button_el = ev.target
            form_el = button_el.parent.parent.parent

            # this allows to use disabled <textearea>, which is normally not
            # sent
            content = form_el.get(selector="textarea")[0].text

            # change filename according to output
            suffix = form_el.name
            download_path = "as_file/%s.%s" % (cls.filename, suffix)
            form_el.action = join(settings.API_PATH, download_path)

            input_el = form_el.get(selector="input")[0]
            input_el.value = content

        for el in document.get(selector="button.output_download_button"):
            el.bind("click", on_click)

    @classmethod
    def reset(cls):
        """
        Reset the datasets and interface to default values.
        """
        cls.hide()

        cls.values = None
        cls.filename = "fn"
        cls.dc_out_el.text = ""
        cls.oai_out_el.text = ""
        cls.mrc_out_el.text = ""


OutputPicker.bind_download_buttons()
