var tinytest = require('tinytest')
var test = tinytest.test
var assert = tinytest.assert
var await = tinytest.await
var conn = require('./birect-conn')
var server = require('./birect-server')
var client = require('./birect-client')

var port = 8085

test('Start server 1', function() {
	var http = require('http')
	var httpServer = http.createServer((req, res) => { res.end('Hi') })
	await(new Promise((resolve, reject) => {
		httpServer.listen(port, () => {
			console.log("Server listening on", port)
			resolve()
		})
	}))
	
	var birectServer = server.upgradeRequests(httpServer, '/birect/upgrade')
	birectServer.handleJSONReq('Echo', function(req) {
		return new Promise((resolve) => {
			resolve({ Text:req.Text })
		})
	})
})

test('Echo client', function() {
	var c = await(client.connect("ws://localhost:"+port+"/birect/upgrade"))
	var res = await(c.sendJSONReq("Echo", { Text:"Foo" }))
	assert(res.Text == 'Foo')
})

test('Start server 2', function() {
	var birectServer = server.listenAndServe(port + 1)
	birectServer.handleJSONReq('Echo', function(req) {
		return new Promise((resolve) => {
			resolve({ Text:req.Text })
		})
	})
	birectServer.handleProtoReq('Echo', function(data) {
		var params = protos.EchoReq.decode(data)
		return new Promise((resolve) => {
			resolve(new protos.EchoRes({ text:params.text }))
		})
	})
})

test('Echo client 2', function() {
	var c = await(client.connect("ws://localhost:"+(port + 1)+"/birect/upgrade"))
	var res = await(c.sendJSONReq("Echo", { Text:"Foo" }))
	assert(res.Text == 'Foo')
})

test('Proto echo client 2', function() {
	var c = await(client.connect("ws://localhost:"+(port + 1)+"/birect/upgrade"))
	var data = await(c.sendProtoReq("Echo", new protos.EchoReq({ text:'Foo' })))
	var res = protos.EchoRes.decode(data)
	assert(res.text == 'Foo')
})

// Misc
///////

var protos = require('protobufjs').loadProto(`
	syntax = "proto3";
	package protos;
	message EchoReq { string text = 1; };
	message EchoRes { string text = 1; };
`).build('protos')

@@ -660,38 +660,16 @@
 urn 
-new 
 Promise
-((resolve) =%3E %7B%0A%09%09%09
+.
 reso
@@ -687,29 +687,24 @@
 req.Text %7D)%0A
-%09%09%7D)%0A
 %09%7D)%0A%7D)%0A%0Atest
@@ -1045,38 +1045,16 @@
 urn 
-new 
 Promise
-((resolve) =%3E %7B%0A%09%09%09
+.
 reso
@@ -1076,21 +1076,16 @@
 Text %7D)%0A
-%09%09%7D)%0A
 %09%7D)%0A%09bir
@@ -1190,38 +1190,16 @@
 urn 
-new 
 Promise
-((resolve) =%3E %7B%0A%09%09%09
+.
 reso
@@ -1244,21 +1244,16 @@
 ext %7D))%0A
-%09%09%7D)%0A
 %09%7D)%0A%7D)%0A%0A

Use Promise.resolve() shorthand