#!/usr/bin/env python
import re
import json
import base64

import baker
import requests

from user import User, UserPassword
from passwordly import generatePassword, createHash, checkHash

from util import db
import config

@baker.command
def signup(username):
  User.signup(db, username)
  return 'Signup completed.'

@baker.command
def process_logs():
  with open('event.log', 'a') as eventlog:
    data = db.lpop('events')
    eventlog.write(data+"\n")

  details = json.loads(data)

  properties = details.copy()

  # Grab all the additional properties
  properties.update(details['properties'])
  del properties['properties']
    
  properties["token"] = config.mixpanel_token
  properties["time"] = int(properties['timestamp'])
  properties['ip'] = properties['remote_addr']
  properties['$os'] = properties['platform']
  properties['$browser'] = properties['browser']
  properties['$referrer'] = properties['referrer']

  del properties['timestamp']
  del properties['platform']
  del properties['browser']
  del properties['referrer']

  params = {"event": details['event'], "properties": properties}
  print params
  data = base64.b64encode(json.dumps(params))
  url = "http://api.mixpanel.com/track/?data=" + data

  print requests.get(url)


if __name__ == '__main__':
  baker.run()
