import pandas as pd  # Module made to filter and analyze data
from datetime import datetime, timedelta  # Module for string->date parsing /// date->string formatting


class DataSet:
    def __init__(self, file, date_col, columns):
        self.file = file
        self.data = pd.read_csv(self.file)
        self.data[date_col] = pd.to_datetime(self.data[date_col], format='%m/%d/%Y %H:%M:%S %p')
        self.date_col = date_col
        self.attributes = columns
        self.set_bw_1mnth_3yrs()
        self.filter_columns()

    def set_bw_1mnth_3yrs(self):
        """Filter date range of the data to be between 3 years and 1 month ago."""
        end_date = (datetime.now() - timedelta(days=30.5)).strftime('%m/%d/%y %H:%M:%S %p')  # 1 month ago
        start_date = (datetime.now() - timedelta(days=(365.25*3))).strftime('%m/%d/%y %H:%M:%S %p')  # 3 years ago
        # update data-frame object to reflect filter
        self.data = self.data[(self.data[self.date_col] < datetime.strptime(end_date, '%m/%d/%y %H:%M:%S %p')) &
                              (self.data[self.date_col] > datetime.strptime(start_date, '%m/%d/%y %H:%M:%S %p'))]

    def filter_columns(self):
        """Filter attributes of data to keep important ones."""
        self.data = self.data[(self.data['IS_TRAFFIC'] == 0)] .filter(self.attributes)

    def get_json(self):
        """Converts dataframe to json string"""
        return self.data.to_json(orient='records')

