import os
import pandas as pd
from pathlib import Path
from pyadlml.constants import START_TIME, END_TIME, DEVICE, VALUE, TIME, ACTIVITY
from pyadlml.dataset._core.activities import ActivityDict

DATA_NAME = 'devices.csv'
DEV_MAP_NAME = 'device_map.csv'
ACT_MAP_NAME = 'activity_map.csv'
ACT_NAME = 'activities_subject_%s.csv'
MAP_ID = 'id'

def _read_activities(path_to_file: Path, path_to_mapping: dict):
    """
    """
    activities = pd.read_csv(path_to_file)
    act_map = pd.read_csv(path_to_mapping, index_col=MAP_ID)\
                .to_dict()[ACTIVITY]
    activities[ACTIVITY] = activities[ACTIVITY].map(act_map)
    activities[START_TIME] = pd.to_datetime(activities[START_TIME])
    activities[END_TIME] = pd.to_datetime(activities[END_TIME])
    return activities


def _read_devices(path_to_dev_file, path_to_mapping):
    devices = pd.read_csv(path_to_dev_file)
    dev_map = pd.read_csv(path_to_mapping, index_col=MAP_ID)\
                .to_dict()[DEVICE]

    devices[DEVICE] = devices[DEVICE].map(dev_map)
    devices[VALUE] = devices[VALUE].astype(str).replace({
        "0": False, "0.0": False, 
        "1": True, "1.0": True,
        "True":True, "False": False,
        "true":True, "false": False,
    })
    devices[TIME] = pd.to_datetime(devices[TIME])
    devices = devices.reset_index(drop=True)
    return devices


def _read_activity_list(path_to_file):
    lst_activities = pd.read_csv(path_to_file)
    return list(lst_activities[ACTIVITY])


def _read_device_list(path_to_file):
    lst_devices = pd.read_csv(path_to_file)
    return list(lst_devices[DEVICE])


def load(folder_path: str, subjects:list=[], retain_corrections=False) -> dict:
    """
    Loads a dataset generated by activity-assistant from a specified folder.

    Parameters
    ----------
    folder_path : str
        The path to the folder where the dataset is located.

    subjects : list of str
        The subjecst names that are to be included. If the activity file
        is named *activities_subject_foo.csv*, then *foo* is the corresponding name.

    Examples
    --------
    The dataset ``my_dataset.zip`` is extracted in the folder ``/path/to/``.

    >>> from pyadlml.dataset import load_act_assist
    >>> data = load_act_assist('/path/to/my_dataset/', subjects=['chris'])

    Returns
    -------
    data : object
    """
    assert isinstance(folder_path, str) or isinstance(folder_path, Path)
    assert isinstance(subjects, list)

    df_dev = _read_devices(Path(folder_path).joinpath(DATA_NAME),
                           Path(folder_path).joinpath(DEV_MAP_NAME))

    # get mappings
    lst_dev = _read_device_list(Path(folder_path).joinpath(DEV_MAP_NAME))
    lst_act = _read_activity_list(Path(folder_path).joinpath(ACT_MAP_NAME))

    #data = Data(None, df_dev, activity_list=lst_act, device_list=lst_dev)



    # If no subjects where specified read the files from the folder following the naming schemata
    if not subjects:
        for fp in Path(folder_path).iterdir():
            if ACT_NAME[:18] in fp.name:
                subjects.append(fp.name[19:-4])

    act_dct = ActivityDict()
    for subject in subjects:
        df_act = _read_activities(Path(folder_path).joinpath(ACT_NAME%(subject)),
                                  Path(folder_path).joinpath(ACT_MAP_NAME))
        act_dct[subject] = df_act

    return dict(
        devices=df_dev,
        device_list=lst_dev,
        activities=act_dct,
        activity_list=lst_act,
    )
