#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

 
#define BTADDR "00:A0:96:1F:21:80"
#define CHANNEL 4


int getSizeFromFile(char filename[], size_t *fileSize) {
	FILE *file_ptr;
	printf("Filename: %s \n",filename);
	file_ptr = fopen(filename,"rb");

	if (file_ptr != NULL) {
		printf("File opened\n");
		// read the file size by 
		// setting the file pointer to the end
		fseek(file_ptr, 0, SEEK_END);
		*fileSize = ftell(file_ptr);
		printf("Filesize: %i Byte\n",*fileSize);
		fclose(file_ptr);
	} else {
		perror("File cannot be opened.");
		exit(1);
	}
	return 0;
}


int getDataFromFile(char filename[],char buffer[]) {
	FILE *file_ptr;
	int count;
	char buf = 0;

	file_ptr = fopen(filename,"rb");
	if(file_ptr != NULL) {
		printf("File opened\n");
		// read from file
		while (!feof(file_ptr)){
			//fread(buffer,sizeof(char),1,file_ptr);
			buf = fgetc(file_ptr);
			buffer[count] = buf;
			count++;
		}
		fclose(file_ptr);
	} else {
		perror("File cannot be opened");
		exit(2);
	}
	return 0;
}


int main(void) {
	// -- open and read file --
	char filename[67];
	size_t fileSize;
	printf("Which File? \n");
	gets(filename);
	 
	// get filesize and create a buffer
	getSizeFromFile(filename, &fileSize);
	char fileBuf[fileSize];
	// read data from the file
	getDataFromFile(filename, fileBuf);
	printf("Buffer size: %i\n",sizeof(fileBuf));
	 
	// -- bluetooth socket work --
	int sock;
	struct sockaddr_rc laddr, raddr;
	struct hci_dev_info di;
	int byte;
	if (hci_devinfo(0, &di) < 0) {
		perror("HCI device info failed");
		exit(1);
	}
	laddr.rc_family = AF_BLUETOOTH;
	laddr.rc_bdaddr = di.bdaddr;
	laddr.rc_channel = 0;
	raddr.rc_family = AF_BLUETOOTH;
	str2ba(BTADDR,&raddr.rc_bdaddr);
	raddr.rc_channel = htobs(CHANNEL);

	sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
	if (sock < 0) {
		perror("socket");
		exit(1);
	}
	if (bind(sock, (struct sockaddr *)&laddr, sizeof(laddr)) < 0) {
		perror("bind");
		exit(1);
	}
	if (connect(sock, (struct sockaddr *)&raddr, sizeof(raddr)) < 0) {
		perror("connect");
		exit(1);
	}

	printf("Connected.\nPress enter to send!");
	char test[2];
	gets(test);

	// send data
	byte = send(sock,fileBuf,sizeof(fileBuf),0);
	if (byte > 0) {
		printf("Sent %i Byte(s)\n",byte);
	} else {
		perror("Error while sending");
		exit(1);
	}

	close(sock);
	return 0;
}
