/*
 * iricore_socket.h
 *
 *  Created on: 7.8.2012
 *      Author: lis
 */
// This program is free software; you can redistribute it and/or
// modify it under the terms of the BUT OPEN SOURCE LICENCE
// Version 1 as published by the Brno University of Technology, Antonínská 548/1,
// 601 90, Czech Republic.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// BUT OPEN SOURCE LICENCE (BUTOSL) for more details.
// 
// You should have received a copy of the BUT OPEN SOURCE LICENCE (BUTOSL)
// along with this program; if not, write to the Brno University of Technology,
// Antonínská 548/1, 601 90, Czech Republic.


#ifndef IRICORE_SOCKET_H_
#define IRICORE_SOCKET_H_

extern "C"{
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
}

#include <string>
#include <sstream>

#include "ndwatch/ipv6.h"

#include "dhcpv6.h"
#include "lease_table.h"

#define IRICOL "/tmp/iricol"

class Lease_table_item;

class unix_socket
{
private:
	int _s, _t, _len;
	struct sockaddr_un _remote;
	std::string _module_name;
	char _str[100];
	bool _connect;
public:
	unix_socket(string module_name = "Unnamed module",bool connect_to_iri = true):
		_s(0), _t(0), _len(0), _remote(){

		_connect = connect_to_iri;
		_module_name = module_name;
		connectSocket();
	}

	void connectSocket(){

		if(_s) close(_s);

		if ((_s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
			perror("socket");
		}
		_remote.sun_family = AF_UNIX;
		strcpy(_remote.sun_path, IRICOL);
		_len = strlen(_remote.sun_path) + sizeof(_remote.sun_family);

		if(_connect){
			if (connect(_s, (struct sockaddr *)&_remote, _len) == -1) {
				perror((std::string("Unable to connect to IRI-CORE \"") + IRICOL +"\"").c_str());
			}
		}
	}
	int send_report(Lease_table_item &item ,time_t timestamp, std::string report_type, std::string description = "");

	~unix_socket(){
		close(_s);
	}
};


#endif /* IRICORE_SOCKET_H_ */
