import logging
from pathlib import Path

from jinja2 import Environment, PackageLoader, select_autoescape

from ee.doit import DoItConfig, Report

logger = logging.getLogger(__name__)

doit_config = DoItConfig()


def _create_env():
    return Environment(
        loader=PackageLoader("ee.report.doit", "templates"),
        autoescape=select_autoescape(["html", "xml"])
    )


def task_report_messages():
    doit_config.report_collection.add_report(Report(task_report_messages))

    def action():
        logger.debug("Generating messages report")

        data_sets = doit_config.dsm.all_data_sets

        logger.debug("Loading {} data sets".format(len(data_sets)))

        ds = doit_config.dsm.load_data_sets(data_sets)

        messages = [o for o in ds.items() if o.object_type.name == "message"]
        logger.debug("Found {} messages".format(len(messages)))

        report_dir = Path(doit_config.extra_config["report_dir"])
        report_dir.mkdir(exist_ok=True)

        with open(report_dir / "messages.rst", "w") as f:
            env = _create_env()
            template = env.get_template("messages.rst.j2")
            f.write(template.render(messages=messages))

    return {
        "actions": [action]
    }


def task_make_reports():
    def action():
        report_dir = Path(doit_config.extra_config["report_dir"])
        report_dir.mkdir(exist_ok=True)

        with open(report_dir / "index.rst", "w") as f:
            env = _create_env()
            template = env.get_template("index.rst.j2")
            f.write(template.render())

    return {
        "actions": [action],
        "task_dep": [r.task.__name__[5:] for r in doit_config.report_collection.reports]
    }