 # Vendor
 Promise = require 'bluebird'
-gapi = Promise.promisifyAll require "googleapis"
+gapi = require "googleapis"
 _find = require 'lodash-node/modern/collections/find' # to be replaced w/ array.prototype.find w/ node --harmony
 gh = require './github'
 

      Info: 'info'
      Search: 'search'

    new Promise (resolve, reject) ->
      current = data[0].rows.filter (cmd) -> cmd[0] != "(not set)"
      prior = data[1].rows

      _transform = (d) ->
        cmdName = util.removeSlash d[0]
        cmdName = cmdName.charAt(0).toUpperCase() + cmdName.slice 1 # Cap Case
        d[0] = cmdName
        d[1] = +d[1]
        d[2] = +d[2]
        return
      current.forEach _transform
      prior.forEach _transform

      cmdCheck = (d) -> d[0].indexOf("ed") is -1 # and d[0] != "Searched"
      # keep only cmds that isn't called on success; 'Searched' is deprecated
      result = current.filter (d) -> cmdCheck d
        .map (d) ->
          cmd: d[0]
          order: order[d[0]]
          icon: icon[d[0]]
          metrics: [
            {metric: 'users', order: 1, current: d[1]} # ga:users
            {metric: 'uses', order: 2, current: d[2]} # ga:pageviews
          ]

      getValue = (cmd, period, ed, valueType) ->
        ed = if ed then 'ed' else ''
        i = if valueType is 'users' then 1 else 2 # else pkgs
        # catch edge case in case new cmd tracked and no prior history
        try
          _find(period, (d) -> d[0] is cmd.cmd + ed)[i]
        catch error
          0 # if not found, cmd tracking wasn't implemented

      result.forEach (cmd) ->
        # cmd with pkgs count ('-ed')
        if ["Install", "Uninstall", "Register", "Unregister"].indexOf(cmd.cmd) != -1
          cmd.metrics.push {
            metric: 'pkgs', order: 3
            current: getValue cmd, current, true, 'pkgs'
          }

        cmd.metrics.forEach (metric) ->
          metric.prior = getValue cmd, prior, (if metric.metric is 'pkgs' then true else false), metric.metric
          metric.delta = metric.current / metric.prior - 1
          return

        return

      resolve result; return

queries.pkgs =
  # 'package' is a reserved word in JS
  # only want to pull pkgs w/ >= 5 installs, which is around the 3500th pkg sorted by installs
  # hence max-results = 5000
  queryObjs: [
    { # current week
      'ids': 'ga:' + config.ga.profile

      'end-date': 'yesterday'
      'metrics': 'ga:users,ga:pageviews'
      'dimensions': 'ga:pagePathLevel2'
      'filters': 'ga:pagePathLevel1=@installed' # =@ contains substring, don't use url encoding '%3D@'
      'sort': '-ga:pageviews'
      'max-results': 3500
    }
