# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from java.net import URL

from org.python.core.util import FileUtil

from com.google.gson.reflect import TypeToken
from com.google.gson import Gson

from client import Data, DataList

def interact(method, urlstr, typ, body):
    con = (URL(urlstr)).openConnection()
    con.setRequestMethod(method)
    con.addRequestProperty('accept',  typ)
    if body != None:
        con.addRequestProperty('content-type', typ)
        con.setDoOutput(True)
        fout = FileUtil.wrap(con.outputStream)
        fout.write(body)
        fout.flush()
    sb = ''
    con.connect()
    if con.responseCode // 100 == 2:
        fin = FileUtil.wrap(con.inputStream)
        for line in fin:
            sb = sb + line
        fin.close()
    else:
        print('Error: %d %s' % (con.responseCode, con.responseMessage))
    con.disconnect()
    return sb

def testGetOne(urlstr, v):
    response = interact('GET', urlstr + '/' + str(v), 'application/json', None)
    gson = Gson()
    d = gson.fromJson(response, Data)
    print(d)

def testGetAll(urlstr):
    response = interact('GET', urlstr, 'application/json', None)
    gson = Gson()
    result = gson.fromJson(response, DataList.getType())
    print(result.get('data'))

def testGetSome(urlstr, start, finish):
    response = interact('GET', urlstr + '?start=' + str(start) + '&finish=' + str(finish), 'application/json', None)
    gson = Gson()
    result = gson.fromJson(response, DataList.getType())
    print(result.get('data'))

def testAdd(urlstr, d1):
    gson = Gson()
    request = gson.toJson(d1)
    response = interact('POST', urlstr + '/', 'application/json', request)
    d2 = gson.fromJson(response, Data)
    print(d2)

def testUpdate(urlstr, v):
    response = interact('GET', urlstr + '/' + str(v), 'application/json', None)
    gson = Gson()
    d = gson.fromJson(response, Data)
    d.xv = d.xv + 0.01
    d.sv = d.sv + ' - updated'
    request = gson.toJson(d)
    interact('PUT', urlstr + '/' + str(v), 'application/json', request)

def testRemove(urlstr, v):
    interact('DELETE', urlstr + '/' + str(v), 'application/json', None)

def test(urlstr):
    testGetOne(urlstr, 2)
    testGetAll(urlstr)
    testGetSome(urlstr, 2, 3)
    testAdd(urlstr, Data(4, 4.4, 'Text #4'))
    testGetAll(urlstr)
    testGetSome(urlstr, 2, 3)
    testUpdate(urlstr, 2)
    testGetAll(urlstr)
    testRemove(urlstr, 4)
    testGetAll(urlstr)

test('http://localhost:8080/api/data')
#test('http://localhost:8080/rest/api/data')
