"""The base components for making apps from DAGs"""

import streamlit as st
from dagapp.utils import check_configs, get_default_configs
from dagapp.page_funcs import SimplePageFunc


def dag_to_page_name(dag):
    return f'{list(dag.leafs)[0].capitalize()} Calculator'


def get_page_callbacks(dags, page_names, page_factory, configs):
    return [
        page_factory(dag, page_name, **config)
        for dag, page_name, config in zip(dags, page_names, configs)
    ]


def get_pages_specs(dags, page_factory, configs):
    """
    Return a mapping of page names to page callback objects.

    The `configs` argument is an iterable of per-dag config dicts. If a config
    provides `page_name` or `page_title` that string will be used as the page
    name (and as the page title passed to the page factory). Otherwise a name
    is autogenerated from the dag via `dag_to_page_name`.
    """
    page_names = []
    for dag, config in zip(dags, configs):
        # Prefer explicit config keys; fall back to autogenerated title
        page_name = None
        if isinstance(config, dict):
            page_name = config.get('page_name') or config.get('page_title')
        if not page_name:
            page_name = dag_to_page_name(dag)
        page_names.append(page_name)

    page_callbacks = get_page_callbacks(dags, page_names, page_factory, configs)
    return dict(zip(page_names, page_callbacks))


def dag_app(dags, page_factory=SimplePageFunc, configs=None):
    if configs is None:
        configs = get_default_configs(dags)

    check_configs(dags, configs)

    # st.set_page_config(layout="wide")

    pages = get_pages_specs(dags, page_factory, configs)

    st.sidebar.title('Navigation')
    page = st.sidebar.radio('Select your page', tuple(pages.keys()))

    pages[page]()
