#!/usr/bin/env ruby

require 'httpclient'
require 'date'
require 'securerandom'
require 'cgi'
require 'time'

# HARD CODED PARAMS ON EN-DEMO, IF YOU TOUCH EN-DEMO THIS MIGHT CHANGE!!

def log_requests
  [ {:code => "409",
     :request => CGI.escape('/transactions/authrep.xml?provider_key=XXX&app_id=YYYY&usage[bla]=1'),
     :response => CGI.escape('<?xml version="1.0" encoding="UTF-8"?><error code="provider_key_invalid">provider key "XXX" is invalid</error>')} ,
	   {:code => "200",
      :request => CGI.escape('/transactions/list_available.xml'),
      :response => CGI.escape('<?xml version="1.0" encoding="UTF-8"?><transactions><transaction id=234/><transaction id=9831124233/><transaction id=23/><transaction id=102/></transactions>')}
  ]
end

#start_date = Time.parse("2011-12-10")
#end_date = Time.parse("2012-01-10")
#num = 10

def ensure_list(x)
  x.is_a?(Array) ? x : [x]
end

def generate_traffic(providers = [] )

  log_requests = log_requests()
  end_point = "http://su1.3scale.net"
  start_date = Time.now - 3600
  end_date = Time.now

  num = 2
  prob = 0.90

  i = 0
  len = end_date - start_date

  # bug #3456
  providers.each do |p_id, p |
    p[:services].each do |ser_id, service|

      s = "provider_key=#{p[:provider_key]}&service_id=#{ser_id}"
      s << "&service_token=#{service[:service_token]}" if service[:service_token]
      data = false

      service[:apps].each do |a|

        metrics = a[:metrics] ? ensure_list(a[:metrics]) : service[:metrics]

        metrics.each do |m|
          if rand() < prob
            num.times do |j|
              val = rand(len.to_i)
	            logi = rand(log_requests.size)
              time = start_date + val
              s << "&transactions[#{i}][user_key]=#{a[:user_key]}"unless a[:user_key].nil?
              s << "&transactions[#{i}][app_id]=#{a[:app_id]}"unless a[:app_id].nil?
              s << "&transactions[#{i}][app_key]=#{a[:app_key]}" unless a[:app_key].nil?
              s << "&transactions[#{i}][timestamp]=#{CGI.escape(time.to_s)}"
              s << "&transactions[#{i}][usage][#{m}]=#{a[:usage] || rand(20)+1}"
              s << "&transactions[#{i}][log][code]=#{log_requests[logi][:code]}"
              s << "&transactions[#{i}][log][request]=#{log_requests[logi][:request]}"
              s << "&transactions[#{i}][log][response]=#{log_requests[logi][:response]}"
              data=true
              i+=1
            end
          end
        end
      end

      if !providers.empty?
        res = HTTPClient.post("#{end_point}/transactions.xml", s )
        puts "fakedata: Added faked data to en-demo #{end_date} service #{ser_id}" if res.status < 300
      end

    end
  end

end


def generate_signups(providers, prefix)
  base_url = '/admin/api/signup.xml'
  date = Date.today.strftime("%Y%m%d")
  providers.each do |(name, p)|
    (p[:count]).times do |i|
      id = "#{date}-#{prefix}-#{i}"
      pass = SecureRandom.hex(10)
      sleep(10)
      r = HTTPClient.post("#{p[:domain]}#{base_url}", {provider_key: p[:provider_key], org_name: "org-#{id}",
                                                       username: "user-#{id}", email: "#{id}@3scaletest.net",
                                                       password: pass })
      puts "generated user #{r.body}"
    end
  end
end


def fake_data
  data = eval(DATA.read)

  traffic = data[:traffic]
  signups = data[:signups]

  # Everyday traffic
  providers = traffic['all']
  generate_traffic(providers)

  #SingleDay traffic
  day_of_month = Time.now.strftime('%d')
  if today_traffic = traffic[day_of_month]
    generate_traffic(today_traffic)
  end

  #Everyday signups
  daily_signups = signups['all']
  generate_signups(daily_signups, SecureRandom.hex(2))
end

fake_data


__END__

{ traffic:
    { 'all' => {
        '2445580880592' =>
        {
          org_name: '3scale Enterprise Demo',
          provider_key: '62686cf1497b0ad582e558e064b11539',
          services: {
            '2555417718602' => { name: 'Metadata API',
                                 # metrics: ['2555417818502'],
                                 metrics: ['hits'],
                                 apps: [{id: '1409610830722' , user_key: 'ba783ea1a04e68d12cc29182ead5dbe0'}]
                               },

            '2555417718592' => { name: 'Voice API',
                                 # metrics:["2555417818492"],
                                 metrics:["hits"],
                                 apps: [{id: '1409610830282' , user_key: 'f061fbd276564cb0c06c1af755c6d6c6'} ,
                                        {id: '1409610830682' , user_key: '4fb0a8cabb8745639046d96e5f0cfd1c'}]
                               },

            '2555417718582' => { name: 'sms API',
                                 # metrics: ['2555417818482'],
                                 metrics: ['hits'],
                                 apps:[{id: '1409610830672' , user_key: 'bfaebc9e8f6cc2349059f06e27106f0e'},
                                       {id: '1409610830272' , user_key: '6a7ff7bc985801f4a5b57ed1c4c830a1'}]
                               },

            '2555417715072' => { name: 'API',
                                 metrics: ['hits'],
                                 # metrics: ['2555417801402'],
                                 apps: [{id: '1409610508462', user_key: 'eb5e90ec2cd86baf8de65c7419f95cb9'},
                                        {id: '1409610830262' , user_key: 'b014cb30df0da330107bf841eeed7936'}]
                               },
          }
        },
        'enterprisedemo' => {
          org_name: 'enterprisedemo',
          provider_key: '4e8d8fc2ea7cf03ff81423784952b119',
          services: {

            '1006371742031' => {  name: 'SMS API',
                                  service_token: 'aa64c280297b5cd58a1cd14eeeb46f6ef7a1444eb6ba9cce198c7c98d4afec86',
                                  metrics: ['hits', 'Bandwidth', 'smsEdit', 'sms_delete', 'sms_sent'],
                                  apps: [
                                    {id: '1409607484442', app_id: 'a4d6ffb8'},
                                    {id: '1409607577321', app_id: 'e8779519'},
                                    {id: '1409608787971', app_id: 'd072f57b'},
                                    {id: '1409607146491', app_id: 'ca5b979f'},
                                    {id: '1409608358572', app_id: '6c2b7072'},
                                    {id: '1409607117852', app_id: 'fc19ffd5'},
                                    {id: '1409607146591', app_id: '2e46cbc7'},
                                    # # # more apps in this service...
                                    # # This ones will hit the limits of shitty test plan
                                    {id: '1409612298209', user_key: 'b56a284443c2ca615c601770c14388a7', usage: 51},
                                    {id: '1409612298259', user_key: '24bc27a3e7d4a51583730790434998c4', usage: 51},
                                    {id: '1409612298263', user_key: '16717345869ff91e848e780ce4667477', usage: 51},
                                    {id: '1409612298264', user_key: 'aeb4c0bb5ac764f1b4de78b9a3da9c0d', usage: 51},
                                    {id: '1409612298265', user_key: 'ba33579a4e532de8a43ff0fd2511de5c', usage: 51},
                                    #
                                    # # Integration errors
                                    # {id: '1409612298264', user_key: 'invalid-key' },
                                    # {id: '1409612298265', user_key: 'ba33579a4e532de8a43ff0fd2511de5c', usage: 'a'},
                                    # {id: '1409612298265', user_key: 'ba33579a4e532de8a43ff0fd2511de5c', usage: 1, metrics: ['hats']},
                                    # {id: '1409612298265', user_key: 'ba33579a4e532de8a43ff0fd2511de5c', usage: '', metrics: ['hits']},

                                  ]},
            '1006371742041' => {name: 'VOICE API',
                                metrics: ['hits', 'voice_outbound_sec'],
                                apps: [
                                  { id: '1409607117862', user_key: '6aa071c8c4e44bedfe5a746352f418d6'},
                                  { id: '1409607146501', user_key: '6764ed87d6765f4354c0e2d70d2bbf88'},
                                  { id: '1409607146601', user_key: '6812d7a4e390d67fe96b9f5998ba297c'},
                                  { id: '1409607484452', user_key: '4fec4e6afe85dfe751735a90dfb4bdf6'},
                                  { id: '1409607810872', user_key: '47888b24bd4f4005c2c9559453676e9e'},
                                  { id: '1409607919181', user_key: '95ab03192228c2a14f0269dae3b96e19'},
                                  { id: '1409608358582', user_key: '95b3c8db9e650fa246f497969d47fd95'},
                                  { id: '1409608787981', user_key: 'f7756b761e7fac0816a64caa73d9a4d2'},
                                  { id: '1409607117792', user_key: '3cf6d3b7dcfcd6fc2335ac0c196b1d07'}
                                ]},

            '1006371742051' => {name: 'METADATA API',
                                metrics: ['hits'],
                                service_token: '403c8cf50962fbfbc5c8b5ce6865c0ff702945a7507705a97c7b3b6884d957fc',
                                apps: [
                                  { id: '1409607117811', app_id: '118f4eb5'},
                                  { id: '1409607117872', app_id: '6bf6169b'},
                                  { id: '1409607146511', app_id: 'c480c018'},
                                  { id: '1409607146611', app_id: '5e1cf6a4'},
                                  { id: '1409607467362', app_id: '7686eb68'},
                                  { id: '1409607484462', app_id: 'c7a971c8'},
                                  { id: '1409607810882', app_id: 'a6c33475'},
                                  { id: '1409607919191', app_id: '12d4ebb1'},
                                  { id: '1409608358592', app_id: 'd1c1edc2'},
                                  { id: '1409608787991', app_id: 'a7eccc64'},
                                  { id: '1409610301252', app_id: 'fffddec6'},
                                  { id: '1409611046932', app_id: '7f59e6c9'},
                                ]},

          }
        }
      },
      '05' => {
        'enterprisedemo' => {
          org_name: 'enterprisedemo',
          provider_key: '4e8d8fc2ea7cf03ff81423784952b119',
          services: {
            '1006371742051' => {name: 'METADATA API',
                                metrics: ['hits'],
                                apps: [
                                  { id: '1409607810882', app_id: '793d7f7a', app_key: '7a37a114ce297b49eabe021c9ddd5ed0', usage: 113000},
                                ],
                               },
          }
        }
      },
      '15' => {
        'enterprisedemo' => {
          org_name: 'enterprisedemo',
          provider_key: '4e8d8fc2ea7cf03ff81423784952b119',
          services: {
            '1006371742051' => {name: 'METADATA API',
                                metrics: ['hits'],
                                apps: [
                                  { id: '1409607810882', app_id: '793d7f7a', app_key: '7a37a114ce297b49eabe021c9ddd5ed0', usage: 113000},
                                ],
                               },
          }
        }
      },
      '25' => {
        'enterprisedemo' => {
          org_name: 'enterprisedemo',
          provider_key: '4e8d8fc2ea7cf03ff81423784952b119',
          services: {
            '1006371742051' => {name: 'METADATA API',
                                metrics: ['hits'],
                                apps: [
                                  { id: '1409607810882', app_id: '793d7f7a', app_key: '7a37a114ce297b49eabe021c9ddd5ed0', usage: 113000},
                                ],
                               },
          }
        }
      }
    },

  signups: {
    'all' =>
    {'enterprisedemo' => {
       org_name: 'enterprisedemo',
       domain: 'https://enterprisedemo-admin.3scale.net/' ,
       provider_key: '4e8d8fc2ea7cf03ff81423784952b119',
       count: 0, # disabled signups
     }
    }
  }

}
