/*
 * Copyright (c) 2009 Veselin Georgiev
 *
 * Cutting the bullshit:
 *  all sources here are free software; you can use them for everything you
 *  want. Just don't blame me if something goes wrong; if something happens
 *  (including, but not limited to:
 *     coredumps, formatted harddrives, ping timeouts, winamp sound skips,
 *     fried CPUs, sudden mother-in-law visits, fraglimits, viagra spam,
 *     barking dogs, earthquakes, frog rain, Windows Vista installations,
 *     anrieff playing the bass guitar, dangerous sporks, apocalypse,
 *     concrete donkey, or even Chuck Norris getting your butt kicked...
 *  ), then you know you have been warned. Four times.
 *
 * Btw, Chuck Norris now doesn't code neither Python, nor Ruby. He's hacking
 * with Makefiles.
 */
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <vcclr.h>
#include "queryserver.h"
#include "utils.h"
#include "stdafx.h"
using namespace std;

const char* infile = "C:\\imagedata";

class WebQueryServer: public QueryServer {
	int w, h;
	int bestquery;
	gcroot<Konkurs::Service^> mp;

public:
	WebQueryServer() : mp(gcnew Konkurs::Service) {
		mp->Url = L"http://konkurs.musala.com/Recognition/Service.asmx";
		w = h = 0;
		bestquery = 0x7fffffff;
	}
	~WebQueryServer() {
		delete mp;
	}
	void init(int &width, int &height)
	{
		width = height = 0;
		int n, m;
		int status = mp->Init(0, n, m);
		if (status) {
			cout << status << endl;
			return;
		}
		height = h = n;
		width = w = m;
	}
	int score(int *xdata)
	{
		int ret = 0;
		cli::array<array<unsigned char>^>^ B = gcnew cli::array<array<unsigned char>^> (h);

		for (int i=0; i<h; i++) {
			B[i] = gcnew cli::array<unsigned char> (w);
			for (int j=0; j<w; j++)
				B[i][j] = System::Byte(xdata[i * w + j]);
		}
		int status = mp->Query(0, B, ret);
		//printf("returned %d\n", ret);
		return status ? 999 : ret;
	}
};



QueryServer* new_query_server(void)
{
	return new WebQueryServer;
}

void delete_query_server(QueryServer* qs)
{
	delete static_cast<WebQueryServer*>(qs);
}
