# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS
# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not use the QuantumBlack
# Trademarks or any confusingly similar mark as a trademark for your product,
#     or use the QuantumBlack Trademarks in any other manner that might cause
# confusion in the marketplace, including but not limited to in advertising,
# on websites, or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.

"""``PandasProfilingDataSet`` is an ``AbstractVersionedDataSet`` to generate
pandas profiling report.
See https://github.com/pandas-profiling/pandas-profiling for details.
"""
import copy
from pathlib import Path
from typing import Any, Dict, List

import pandas as pd
import seaborn as sns
from math import ceil
import matplotlib.pyplot as plt

from kedro.contrib.io import DefaultArgumentsMixIn
from kedro.io.core import AbstractVersionedDataSet, DataSetError, Version


class SeabornPairPlotDataSet(DefaultArgumentsMixIn, AbstractVersionedDataSet):
    """``PandasProfilingDataSet`` is an ``AbstractVersionedDataSet`` to generate
    pandas profiling report.
    See https://github.com/pandas-profiling/pandas-profiling for details.
    """

    DEFAULT_SAVE_ARGS = dict()  # type: Dict[str, Any]

    def __init__(
        self,
        filepath: str,
        save_args: Dict[str, Any] = None,
        sample_args: Dict[str, Any] = None,
        version: Version = None,
    ) -> None:
        """Creates a new instance of ``PandasProfilingDataSet`` pointing to a concrete
        filepath.

        Args:
            filepath: path to a local yaml file.
            save_args: Arguments passed on to ``df.profile_report`` such as title.
                See https://pandas-profiling.github.io/pandas-profiling/docs/ for details.
                See https://github.com/pandas-profiling/pandas-profiling/blob/master/pandas_profiling/config_default.yaml for default values.
            sample_args: Arguments passed on to ``df.sample``.
                See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html for details.
            version: If specified, should be an instance of
                ``kedro.io.core.Version``. If its ``load`` attribute is
                None, the latest version will be loaded. If its ``save``
                attribute is None, save version will be autogenerated.

        """
        super().__init__(filepath=Path(filepath), save_args=save_args, version=version)
        self._sample_args = sample_args

    def _describe(self) -> Dict[str, Any]:
        return dict(
            filepath=self._filepath,
            save_args=self._save_args,
            sampling_args=self._sample_args,
            version=self._version,
        )

    def _load(self) -> Any:
        """ loading is not supported. """
        return None

    def _save(self, data: pd.DataFrame) -> None:
        save_path = Path(self._get_save_path())
        save_path.parent.mkdir(parents=True, exist_ok=True)

        if self._sample_args is not None:
            data = data.sample(**self._sample_args)

        save_args = copy.deepcopy(self._save_args)

        cols_all = data.columns.to_list()

        chunk_size = save_args.pop("chunk_size", None)
        if chunk_size:
            x_vars = save_args.pop("x_vars", None)
            y_vars = save_args.pop("y_vars", None)

            p = Path(save_path)
            # ps = p.parent / p.stem
            p.mkdir(parents=True, exist_ok=True)
            i = 0
            for x in _reshape(x_vars or cols_all, chunk_size):
                for y in _reshape(y_vars or cols_all, chunk_size):
                    plt.figure()
                    g = sns.pairplot(data, x_vars=x, y_vars=y, **save_args)
                    plt.suptitle("{} vs {}".format(y, x), va="bottom")
                    s = p / "{}_{:d}{}".format(p.stem, i, p.suffix)
                    i += 1
                    plt.savefig(s)
                    plt.close("all")
        else:
            plt.figure()
            save_args.setdefault("x_vars", cols_all)
            save_args.setdefault("y_vars", cols_all)
            sns.pairplot(data, **self._save_args)
            plt.savefig(save_path)
            plt.close("all")

    def _exists(self) -> bool:
        try:
            path = self._get_load_path()
        except DataSetError:
            return False
        return Path(path).is_file()


def _reshape(ls: List[Any], size: int) -> List[List[Any]]:
    return [ls[i : i + size] for i in range(0, len(ls), size)]


# def _col_names_from_dtypes(
#     df: pd.DataFrame,
#     include: List[str] =["object"],
# ) -> List[str]:
#     dtypes_dict = df.dtypes.to_dict()
#     return [col for col, dtype in dtypes_dict.items() if dtype.name in include]
