#include "pin.hpp"
#include "systemCall.hpp"
#include <fstream>
#include <iostream>


char buffer[50];
char gpioNo = 17; 
uint8_t currentPin = 0; 
int ck = 0; 
std::ifstream bufFile; 

Pin::Pin()
{
} 

Pin::~Pin()
{

} 

void Pin::setMode(mode mode)
{
	switch(mode)
	{
		case input:
			sprintf(buffer, "echo \"in\" > /sys/class/gpio/gpio%d/direction",gpioNo);
			system(buffer);
			break; 
		case output:
			sprintf(buffer, "echo \"out\" > /sys/class/gpio/gpio%d/direction",gpioNo);
			system(buffer);
			break; 
		case analog:
			std::cout << "No analog pins are awailable for raspberry" << std::endl;
			break; 
		case alternate:
			std::cout << "No analog pins are awailable for raspberry" << std::endl;
			break; 
		default :
			break; 
	}
}
 
void Pin::setOutputState(state state)
{
	
}
 
void Pin::setPullUpDonw(pullUpDown resistance)
{
	
}
 
void Pin::setSpeed(speed speed)
{
	
}
 
void Pin::config(mode mode, state state, pullUpDown resistance, speed speed)
{
	
}
 

bool Pin::read()
{
	sprintf(buffer,"/sys/class/gpio/gpio%d/value",gpioNo);
	bufFile.open(buffer,std::ios::in);
	if(bufFile.is_open())
	{
		bufFile.read(buffer,1);  

		if(buffer[0] == '1')
		{
			bufFile.close();
			return 1; 
		}
		else if (buffer[0] == '0')
		{
			bufFile.close();
			return 0; 
		}
	}
}

bool Pin::toggle()
{
	return 1; 	
}

void Pin::write(bool state)
{
	if(state == 1)
	{
		sprintf(buffer, "echo \"%d\" > /sys/class/gpio/gpio%d/value",state,gpioNo);
		system(buffer);
		return;
	}
	sprintf(buffer, "echo \"%d\" > /sys/class/gpio/gpio%d/value",state,gpioNo);
	system(buffer);
}


void Pin::init()
{
	sprintf(buffer,"[ -d /sys/class/gpio/gpio%d ]",gpioNo); // retunrs null if directory exists
	ck = system(buffer);
	if( ck != 0) 
	{
		sprintf(buffer, "echo \"%d\" > /sys/class/gpio/export",gpioNo);
		ck = system(buffer);
	}
	else
	{
		std::cout << "Pin already initiated"<< std::endl;	
	}
}

void Pin::deInit()
{
	sprintf(buffer,"[ -d /sys/class/gpio/gpio%d ]",gpioNo); // retunrs null if directory exists
	ck = system(buffer);
	if( ck == 0) 
	{
		sprintf(buffer, "echo \"%d\" > /sys/class/gpio/unexport",gpioNo);
		system(buffer);
	}
}


void Pin::hardwareInfo()
{
	
}


void Pin::throwError(uint16_t line, errors errNo)
{
	
}
