# -*- coding:utf-8 -*-

# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP. 
#
# This script is automatically generated by ngrinder.
#
# @author admin
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from net.grinder.plugin.http import HTTPPluginControl
from net.grinder.plugin.http import TimeoutException
from HTTPClient import NVPair

from HTTPClient import Cookie, CookieModule, CookiePolicyHandler
from org.json import JSONObject
import random, datetime, os, copy, logging, time
import com.xhaus.jyson.JysonCodec as json
from java.lang import System

#control = HTTPPluginControl.getConnectionDefaults()
# if you don"t want that HTTPRequest follows the redirection, please modify the following option 0.
# control.followRedirects = 1
# if you want to increase the timeout, please modify the following option.
#control.timeout = 6000

tests = {}
tests["1"] = Test(1, "getaid")

# Make any method call on req increase TPS
urlbase = "http://14.63.226.42:11000/"

class TestRunner:
    account = None
    username = "bot_test_" + str(random.randint(10000, 20000))
    req = None # req = HTTPRequest()
    aid = None
    cid = None
    level = None
    acciteminven = None
    chariteminven = None
    activesoulinven = None
    passivesoulinven = None
    reterror = None
    testlist = []

    def GET(self, url, params = {}):
        global urlbase
        pairs = []
        for k, v in params.iteritems():
            pairs.append(NVPair(k, str(v)))

        pairs.append(NVPair("Debug", str("1")))
        # set cookie before REQUEST if we have
        #if self.cookies:
        #    for cookie in self.cookies:
        #        CookieModule.addCookie(cookie, HTTPPluginControl.getThreadHTTPClientContext())

        try:
            result = self.req.GET(urlbase + url, pairs)
        except TimeoutException:
            grinder.statistics.forLastTest.success = 0

        # set cookie after REQUEST if we had not
        #if not self.cookies and result.getStatusCode() == 200:
        #    self.cookies = CookieModule.listAllCookies(HTTPPluginControl.getThreadHTTPClientContext())

        return result

    def expect(self, substring, response, code=None):   
        assert response.getStatusCode() == 200, "response.getStatusCode(): " + repr(response.getStatusCode())
        try:
            js = json.loads(response.getText())
        except Exception, e:
            grinder.logger.error("response.text: " + str(response.text))
            raise e

        #if code and len(code) > 0:
        #    assert code in js["code"], pretty(js)
        #elif substring and len(substring) > 0:
        if substring and len(substring) > 0:
            grinder.logger.debug("EXPECTS SUBSTR: " + substring + "...")
        #    assert substring in js["message"], pretty(js)
        return js

    # initlialize a thread 
    def __init__(self):
        control = HTTPPluginControl.getConnectionDefaults() 
        control.timeout = 6000
        grinder.statistics.delayReports=True
        pass
        #self.testlist.append(3)
        #self.user_login()

    def __del__(self):
        self.user_logout()

    # test method        
    def __call__(self):
       #totalThreadCount = grinder.getProperties().getInt("grinder.threads", 1);
       #self.aid = grinder.threadNumber + 1;
       #self.aid = random.randrange(2,6) # first eqaul or over, sencond under
       #self.aid = 5
        totalProcessCount = grinder.getProperties().getInt("grinder.processes", 1);
        totalThreadCount = grinder.getProperties().getInt("grinder.threads", 1);               
        self.username = "bot_%d_%08d" % (time.time(), (grinder.agentNumber * totalProcessCount * totalThreadCount) + (grinder.processNumber * totalThreadCount) + grinder.threadNumber)
        js = self.user_getaid();

        if js == None:
            grinder.logger.error("request error")
            grinder.statistics.forLastTest.success = 0;
            return None
        return None

    def user_logout(self):
        grinder.logger.info("logged out : %d" % (self.aid))

    def user_getaid(self):
        global tests
        self.req = HTTPRequest()
        tests["1"].record(self.req)
        e = {"op": "get_user_aid"}
        e["platform_type"] = 10000
        e["user_id"] = self.username
        r = self.GET("RequestPrivateServer.aspx", e)        
        js = self.expect(None, r)
        self.reterror = js["resultcode"];

        if self.reterror == 0:
            self.aid = js["aid"]
            grinder.statistics.forLastTest.success = 1
        else:
            grinder.logger.info("getaid reterror : %d" % (self.reterror))
            grinder.logger.error("request error")
            grinder.statistics.forLastTest.success = 0;
        return js;