#include <stdio.h>
#include <p2k.h>
#include <p2kusb.h>
#include <p2kcmd_fsac.h>


int list_cb(int id, int count, int length, int attrib, int owner, const char* name) {
	printf("%4d %6ld %3d %3d %s\n", id, length, owner, attrib, name );
	return 0;
}

int main (int argc, const char * argv[]) {
	p2k_phone *ph;
	p2k_packet *out, *in;
	char str[P2K_PACKET_DATA_MAX/2];
	int pos, len;
	
	// attempt to connect to phone
	// *** last argument will need to be changed to match your system before compiling this
	printf("Attempting to connect to phone...	");
	ph = p2k_phone_connect_simple(P2K_DEFAULT_AT_VENDOR, P2K_DEFAULT_AT_PRODUCT, 
		P2K_DEFAULT_P2K_VENDOR, P2K_DEFAULT_P2K_PRODUCT,"/dev/ttyACM0");

	if( !ph ) {
		printf("Couldn't connect to phone.\n");
		return 1;
	}
	printf("Successful.\n");

	int fileCount = p2k_fsac_count(ph);
	if(fileCount < 0) {
		printf("Couldn't execute FSAC COUNT.\n");
	} else {
		printf("File count: %d\n", fileCount);
	}

	char volname[256];
	if(p2k_fsac_volname(ph, volname, 256) < 0) {
		printf("Couldn't execute FSAC VOLNAME.\n");
	} else {
		printf("Volume name: %s\n", volname);
	}

	int freeSpace = p2k_fsac_volspace(ph, volname);
	if(freeSpace < 0) {
		printf("Couldn't execute FSAC VOLSPACE.\n");
	} else {
		printf("Free space: %d\n", freeSpace);
	}

	if(p2k_fsac_open(ph, "/a/testfile3", P2K_FILE_NOATTR) != 0) {
		printf("Couldn't execute FSAC OPEN.\n");
	} else {
		printf("File /a/testfile opened successfully\n");
	}

	int writeResult = p2k_fsac_write(ph, (uint8_t*)"testing", 7);
	if(writeResult < 0) {
		printf("Couldn't execute FSAC WRITE.\n");
	} else {
		printf("Wrote %d bytes to file.\n", writeResult);
	}

	if(p2k_fsac_close(ph) != 0) {
		printf("Couldn't execute FSAC CLOSE.\n");
	} else {
		printf("Closed file.\n");
	}

	if(p2k_fsac_open(ph, "/a/testfile3", P2K_FILE_NOATTR) != 0) {
		printf("Couldn't execute FSAC OPEN.\n");
	} else {
		printf("File /a/testfile opened successfully\n");
	}

	char readBuff[20];
	int readResult = p2k_fsac_read(ph, (uint8_t*)readBuff, 20);
	if(readResult < 0) {
		printf("Couldn't execute FSAC READ.\n");
	} else {
		printf("Read %d bytes from file.\n", readResult);
		readBuff[readResult] = 0;
		printf("Read string: %s\n", readBuff);
	}

	if(p2k_fsac_close(ph) != 0) {
		printf("Couldn't execute FSAC CLOSE.\n");
	} else {
		printf("Closed file.\n");
	}

	if(p2k_fsac_delete(ph, "/a/testfile3") < 0) {
		printf("Couldn't execute FSAC DELETE.\n");
	} else {
		printf("Deleted file.\n");
	}

	p2k_fsac_list(ph, list_cb);

	// disconnect the phone
	printf("\nAttempting to disconnect from phone...	");
	p2k_phone_disconnect(ph);
	printf("Successful.\n");
	
	return 0;
}
