// cpptest.cpp
// sdyoung@well.com
//
// A demonstration of the C++ wrapper.  Note that I am not really a C++
// programmer, but this should get the idea across.
//
//   Copyright (c) 2001, 2002 Steven Young
//
//   Permission is hereby granted, free of charge, to any person obtaining
//   a copy of this software and associated documentation files (the
//   "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and/or sell copies of the Software, and to
//   permit persons to whom the Software is furnished to do so, subject to
//   the following conditions:
//
//   The above copyright notice and this permission notice shall be
//   included in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include "libdict-wrap.hpp"

int main(int argc, char **argv) {
	class dictConn dc;
	char optch;
	char *server = "dict.org";
	char *word = "hello";
	char *dict = NULL;
	char *strat = NULL;
	bool listmode = false;
	struct ld_defanswer **defs;
	int idx = 0;
	bool debug = false;

	while((optch = getopt(argc, argv, "s:w:d:t:lD")) != EOF) {
		switch(optch) {
			case 's': 
				server = strdup(optarg);
				break;
			case 'w':
				word = strdup(optarg);
				break;
			case 'd':
				dict = strdup(optarg);
				break;
			case 't':
				strat = strdup(optarg);
				break;
			case 'l':
				listmode = true;
				break;
			case 'D':
				debug = true;
				break;
		}
	}

	if(dc.newConn(server, 0, 0, NULL, debug) == false) {
		cout << "Unable to connect to server." << endl;
		cout << "Reason: ";
		if(dc.getError() == LDERRNO) {
			cout << strerror(errno) << endl;
		} else {
			cout << dc.strError(dc.getError()) << endl;
		}
		exit(0);
	}
	cout << "Server info: " << dc.getServerInfo() << endl;
	if(dict) {
		if(!dc.setDb(dict)) {
			cout << "Invalid database specified." << endl;
			exit(0);
		}
	}
	if(strat) {
		if(!dc.setStrat(strat)) {
			cout << "Invalid strategy specified." << endl;
			exit(0);
		}
	}
	if(!(defs = dc.define(word))) {
		cout << "No words found." << endl;
	} else {
		cout << "Word found, definition follows." << endl;
		idx = 0;
		while(defs[idx]) {
			cout << "Word: " << defs[idx]->ld_answord << " (" << defs[idx]->ld_ansdict << ")" << endl;
			cout << "Definition: " << endl;
			cout << defs[idx]->ld_ansdef << endl << endl;
			idx++;
		}
	}
}
