"""
Module to process Muse data from the mind monitor application
"""

import os
import random

import numpy as np
import pandas as pd


class MuseReader:
    """
    Parses, timeshifts and writes data generated by the Muse S headband using the Mind Monitor application.

    Attributes
    ----------
    data : DataFrame
        dataframe of the read data
    """

    def __init__(self, path):
        """
        Parse the csv file located in the specified directory into a dataframe.

        Parameters
        ----------
        path : str
            path to the csv file
        """
        self.data = pd.read_csv(path, parse_dates=['TimeStamp'], index_col='TimeStamp')

    def write(self, path):
        """
        Writes the dataframe back into a csv file.

        Parameters
        ----------
        path : str
            path to the write file.
        """

        self.data.reset_index().to_csv(path, index=False)

    def timeshift(self, shift='random'):
        """
        Shifts the index column 'TimeStamp'.

        Parameters
        ----------
        shift : None/'random', pd.Timestamp or pd.Timedelta
            If shift is not specified, shifts the data by a random time interval
            between one month and two years to the past.

            If shift is a timdelta, shifts the data by that timedelta.

            If shift is a timestamp, shifts the data such that the earliest entry
            is at that timestamp and the remaining values keep the same
            time distance to the first entry.
        """

        if shift == 'random':
            one_month = pd.Timedelta('- 30 days').value
            two_years = pd.Timedelta('- 730 days').value
            random_timedelta = pd.Timedelta(random.uniform(one_month, two_years))
            self.timeshift(random_timedelta)

        if isinstance(shift, pd.Timestamp):
            timedeltas = self.data.index - self.data.index[0]
            self.data.index = shift + timedeltas

        if isinstance(shift, pd.Timedelta):
            self.data.index += shift
