#!/usr/bin/env ruby

require 'segment/analytics'
require 'rubygems'
require 'commander/import'
require 'time'
require 'json'

program :name, 'simulator.rb'
program :version, '0.0.1'
program :description, 'scripting simulator'

def json_hash(str)
  if str
    return JSON.parse(str)
  end
end

# analytics -method=<method> -segment-write-key=<segmentWriteKey> [options]

default_command :send

command :send do |c|
  c.description = 'send a segment message'

  c.option '--writeKey=<writeKey>', String, 'the Segment writeKey'
  c.option '--type=<type>', String, 'The Segment message type'

  c.option '--userId=<userId>', String, 'the user id to send the event as'
  c.option '--anonymousId=<anonymousId>', String, 'the anonymous user id to send the event as'
  c.option '--context=<context>', 'additional context for the event (JSON-encoded)'

  c.option '--event=<event>', String, 'the event name to send with the event'
  c.option '--properties=<properties>', 'the event properties to send (JSON-encoded)'

  c.option '--name=<name>', 'name of the screen or page to send with the message'

  c.option '--traits=<traits>', 'the identify/group traits to send (JSON-encoded)'

  c.option '--groupId=<groupId>', String, 'the group id'

  c.action do |args, options|
    Analytics = Segment::Analytics.new({
      write_key: options.writeKey,
      on_error: Proc.new { |status, msg| print msg }
    })

    case options.type
    when "track"
      Analytics.track({
        user_id: options.userId,
        event: options.event,
        anonymous_id: options.anonymousId,
        properties: json_hash(options.properties),
        context: json_hash(options.context)
      })
    when "page"
      Analytics.page({
        user_id: options.userId,
        anonymous_id: options.anonymousId,
        name: options.name,
        properties: json_hash(options.properties),
        context: json_hash(options.context)
      })
    when "screen"
      Analytics.screen({
        user_id: options.userId,
        anonymous_id: options.anonymousId,
        name: option.name,
        traits: json_hash(options.traits),
        properties: json_hash(option.properties)
      })
    when "identify"
      Analytics.identify({
        user_id: options.userId,
        anonymous_id: options.anonymousId,
        traits: json_hash(options.traits),
        context: json_hash(options.context)
      })
    when "group"
      Analytics.group({
        user_id: options.userId,
        anonymous_id: options.anonymousId,
        group_id: options.groupId,
        traits: json_hash(options.traits),
        context: json_hash(options.context)
      })
    else
      raise "Invalid Message Type #{options.type}"
    end
    Analytics.flush
  end
end
