import graphlab as gl
import datetime
gl.canvas.set_target('ipynb') # make sure plots appear inline

"""
Explanation: Working with user-activity data
In this notebook, you will learn how to:
Work with user-activity data as a TimeSeries

Import data from a csv.
Explore the data.
Convert the data into TimeSeries.
Perform a few simple aggregations to explore the user-activity data.

Let's get started!
End of explanation
"""


interactions = gl.SFrame.read_csv("data/online_retail_interactions.csv")

interactions

"""
Explanation: Loading data from a flat- ile
Other common sources of data include
- SQL tables
- Spark RDD
- Pandas DataFrames
- Numpy
- Network file systems such as HDFS, S3
End of explanation
"""


interactions['Quantity'].show()

interactions["CustomerID"]

# Make sure all ID columns are interpreted as string
interactions["InvoiceNo"] = interactions["InvoiceNo"].astype(str)
interactions["CustomerID"] = interactions["CustomerID"].astype(str)

interactions["CustomerID"].show()

"""
Explanation: Exploring the data
End of explanation
"""


active_user = interactions[interactions["CustomerID"] == '17841']
active_user

active_user.show(x = 'InvoiceDate', y = 'Quantity', view = 'Bar Chart')

"""
Explanation: What does an active user look like?
End of explanation
"""


inactive_user = interactions[interactions["CustomerID"] == '14388']
inactive_user.show(x = 'InvoiceDate', y = 'Quantity', view = 'Bar Chart')

"""
Explanation: What does an inactive user look like?
End of explanation
"""


users = gl.SFrame.read_csv("data/online_retail_users.csv")

users['CustomerID'] = users['CustomerID'].astype(str)
users

users['user_type'].show()

users.save('data/users.sf')

"""
Explanation: Import & explore user meta-data
End of explanation
"""


interactions['InvoiceDate']

"""
Explanation: 2. Converting activity-data into a TimeSeries
End of explanation
"""


def str_to_datetime(x):
    import dateutil
    from dateutil import parser
    return dateutil.parser.parse(x)

str_to_datetime('12/1/10 14:41')

interactions['InvoiceDate'] = interactions['InvoiceDate'].apply(str_to_datetime)
interactions['InvoiceDate']

"""
Explanation: Convert string to datetime
End of explanation
"""


interactions_ts = gl.TimeSeries(interactions, 'InvoiceDate')

interactions_ts

interactions_ts.save('data/user_activity_data.ts/')

"""
Explanation: Convert SFrame to a TimeSeries
End of explanation
"""


