# coding: utf-8
from .const import CLI_REPORTS, IMG_DIR_PATH, TMP_DIR_PATH
from .source import KeywordsDF, SearchQueriesDF, MobileDF
from .configure_reports import return_report_name
from .review import try_add_review_sheet
from .xlsx_keywords import make_xlsx_keywords
from .xlsx_search_queries import make_xlsx_search_queries
from .xlsx_mobile import make_xlsx_mobile
from .utils import get_max_images
from os.path import isdir
from os import mkdir
import logging
import pandas as pd


def make_keywords(sheets):
    if get_max_images() > 0:
        for x in (IMG_DIR_PATH, TMP_DIR_PATH):
            if not isdir(x):
                mkdir(x)

    df_keywords = KeywordsDF()
    if df_keywords is None or df_keywords.shape[0] == 0:
        return None
    with pd.ExcelWriter(u"./{report_name}.xlsx".format(report_name=return_report_name("keywords")),
                        engine="xlsxwriter") as xlsx_writer:
        logging.debug("BEGIN `keywords`")
        pd.formats.format.header_style["alignment"]["horizontal"] = "left"
        print("{:-<15}".format(""))
        print("\nReports:")
        map(lambda fn: fn(xlsx_writer, df_keywords), make_xlsx_keywords(sheets))
        try_add_review_sheet(xlsx_writer, df_keywords)
        logging.debug("END `keywords`")

    return df_keywords


def make_search_queries(sheets):
    df_queries = SearchQueriesDF()
    if df_queries is None or df_queries.shape[0] == 0:
        return None
    with pd.ExcelWriter(u"./{report_name}.xlsx".format(report_name=return_report_name("search_queries")),
                        engine="xlsxwriter") as xlsx_writer:
        logging.debug("BEGIN `search_queries`")
        pd.formats.format.header_style["alignment"]["horizontal"] = "left"
        print("{:-<15}".format(""))
        print("\nReports:")
        map(lambda fn: fn(xlsx_writer, df_queries), make_xlsx_search_queries(sheets))
        try_add_review_sheet(xlsx_writer, df_queries)
        logging.debug("END `search_queries`")

    return df_queries


def make_mobile(sheets):
    if get_max_images() > 0:
        for x in (IMG_DIR_PATH, TMP_DIR_PATH):
            if not isdir(x):
                mkdir(x)

    df_mobile = MobileDF()
    if df_mobile is None or df_mobile.shape[0] == 0:
        return None
    with pd.ExcelWriter(u"./{report_name}.xlsx".format(report_name=return_report_name("mobile")),
                        engine="xlsxwriter") as xlsx_writer:
        logging.debug("BEGIN `mobile`")
        pd.formats.format.header_style["alignment"]["horizontal"] = "left"
        print("{:-<15}".format(""))
        print("\nReports:")
        map(lambda fn: fn(xlsx_writer, df_mobile), make_xlsx_mobile(sheets))
        try_add_review_sheet(xlsx_writer, df_mobile)
        logging.debug("END `mobile`")

    return df_mobile


REPORTS = dict(zip(CLI_REPORTS, [make_keywords, make_search_queries, make_mobile]))
