import os
import pandas as pd
from pathlib import Path
from logging import getLogger
from save_log import get_version, send_message, dask_mode
import dask.dataframe as dd


class BaseClassifier():
    def __init__(self, params, dataset_name):
        os.environ['KMP_DUPLICATE_LIB_OK'] = "True"
        self.params = params
        self.dataset_name = dataset_name

    def get_feature_df(self, feature_names, valid_dir, part):
        """
        Ex)
        dataset_name    : min, ...
        feature_names   : __preprocess() return
        valid_dir       : "valid0", "valid1", ...
        part            : "train", "validate", "test"
        """
        feature_df = None
        feature_set_path = Path(__file__).absolute().parents[2] / "data" / "features" / self.dataset_name / valid_dir
        if dask_mode():
            print("Using dask.dataframe.read_csv()")

        for group, feature_list in feature_names.items():

            getLogger(get_version()).info("\t \t \t Reading {}_{}.csv...".format(part, group))
            send_message("\t \t \t Reading {}_{}.csv...".format(part, group))
            if dask_mode():
                df = dd.read_csv(feature_set_path / "{}_{}.csv".format(part, group),
                                 usecols=["MachineIdentifier"] + feature_list)
                df = df.compute()
            else:
                df = pd.read_csv(feature_set_path / "{}_{}.csv".format(part, group),
                                 usecols=["MachineIdentifier"] + feature_list)

            if feature_df is None:
                feature_df = df
            else:
                feature_df = feature_df.merge(right=df,
                                              how="inner",
                                              on="MachineIdentifier")

        if part in ["train", "validate"]:
            if dask_mode():
                HasDetections = dd.read_csv(Path(__file__).absolute().parents[2] / "input" / "train.csv",
                                            usecols=["MachineIdentifier", "HasDetections"])
                HasDetections = HasDetections.compute()
            else:
                HasDetections = pd.read_csv(Path(__file__).absolute().parents[2] / "input" / "train.csv",
                                            usecols=["MachineIdentifier", "HasDetections"])
            feature_df = feature_df.merge(right=HasDetections,
                                          on="MachineIdentifier",
                                          how="inner")
        return feature_df
