/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

#include <string>
#include <iostream>
#include <direct.h>

// including DAS headers
#include <apache/das/rdb/Connection.h>
#include <apache/das/rdb/DASImpl.h>
#include <apache/das/rdb/SQLException.h>
#include <apache/das/CommandPtr.h>

// including SDO header
#include <commonj/sdo/DataObject.h>

using namespace apache::das::rdb;
using namespace apache::das;
using namespace commonj::sdo;
using namespace std;

std::string clearDBStatements[] = {	"delete from employee",
									"delete from department",
									"delete from company",
									"drop table employee",
									"drop table department",
									"drop table company"
								  };

std::string resetDBStatements[] = {	"create table company ( id int not null, name varchar(20), primary key(id) )",
									"create table department ( id int not null, name varchar(20) not null, company_id int, foreign key (company_id) references company (id), primary key(id, name) )",
									"create table employee ( id int not null, name varchar(20), department_id int, department_name varchar(20), primary key(id) )",
									"insert into company values (1, 'apache')",
									"insert into company values (2, 'acme')",
									"insert into company values (3, 'google')",
									"insert into company values (4, 'ibm')",
									"insert into company values (5, 'yahoo')",
									"insert into department values (1, 'department1', 1)",
									"insert into department values (2, 'department1', 1)",
									"insert into department values (3, 'department2', 2)",
									"insert into department values (5, 'department3', 3)",
									"insert into department values (4, 'department5', 2)",
									"insert into department values (6, 'department6', 3)",
									"insert into employee values (1, 'adriano', 1, 'department1')",
									"insert into employee values (2, 'paul', 1, 'department1')",
									"insert into employee values (3, 'richard', 1, 'department1')",
									"insert into employee values (4, 'ema', 2, 'department2')",
									"insert into employee values (5, 'james', 2, 'department2')"
								};

Connection* getConnection() {
	Connection* conn;

	try {
		//Connect to a database using a DSN
		std::string dsn = "DASCompanySample";
		std::string user = "postgres";
		std::string password = "tuscany";

		conn = new Connection(dsn, user, password);
		
	} catch (SQLException& ex) {
		cout << "couldn't connect to the data source: " << ex.what() << endl;
		system("PAUSE");
		exit(1);

	}

	// Create and populate the database tables

	StatementPtr stmt = conn->createStatement();

	for (unsigned int i = 0 ; i < 6 ; i++) {

		try {
			stmt->executeQuery(clearDBStatements[i]);
		} catch (SQLException& ex) {cout << ex.what() << endl;}

	}

	for (unsigned int i = 0 ; i < 19 ; i++) {

		try {
			stmt->executeQuery(resetDBStatements[i]);
		} catch (SQLException& ex) {cout << ex.what() << endl;}
	
	}

	// Commit the changes
	stmt->executeQuery("commit");
	
	return conn;

}

void main() {
	ConfigImpl config("../rsc/sampleConfig.xml");
	
	// Get a connection
	Connection* connection = getConnection();
	
	// Create a DAS instance providing a connection using a factory 
	DASImpl* das = (DASImpl*) DASImpl::getFACTORY().createDAS(config, *connection);

	// Get a SQL command from the config
	CommandPtr command = das->getCommand("get all tables");

	// Execute the sql command and generate a SDO graph with the returned data
	DataObjectPtr root = command->executeQuery();

	// Get all companies
	DataObjectList& companyList = root->getList("COMPANY");
	
	// Print each company id and name
	for (int i = 0 ; i < companyList.size() ; i++) {
		// Get the company id
		long id = companyList[i]->getInt("ID");

		// Get the name string length and allocate enough space for it
		unsigned int stringLength = companyList[i]->getLength("NAME");
		wchar_t* buffer = new wchar_t[stringLength];

		// Get the company name
		companyList[i]->getString("NAME", buffer, stringLength);
		wstring name = wstring(buffer, stringLength);

		// Print the company data
		wcout << "Company: " << i << endl;
		wcout << "   id = " << id << endl;
		wcout << "   name = " << name << endl << endl;

		// Free the allocated memory
		delete [] buffer;

	}

	// Get a company named "apache"
	DataObjectPtr company = root->getDataObject("COMPANY[NAME='apache']");

	// Remove the first department of this company and get it
	commonj::sdo::DataObjectPtr department = company->getList("DEPARTMENT").remove(0);;
	
	// Change the company name to "amd"
	wstring companyName = L"amd";
	company->setString("NAME", companyName.c_str(), companyName.size());

	// The department is added to the company named "ibm"
	root->getDataObject("COMPANY[NAME='ibm']")->getList("DEPARTMENT").append(department);

	// The graph changes are persited on the database
	das->applyChanges(root);
	
	// Free the allocated connection and DAS instance
	delete das;
	delete connection;

	system("PAUSE");

}
