/**
 * @file ft_sender.c
 *
 * @brief This file contains functions that provides demonstration of
 *        usage of state machine APIs
 *
 * The functions provided in the file provides demonstration on
 * usage of state machine APIs
 */
#include <stdio.h>

#include "ft_sender.h"
#include "file_transfer.h"
#include "fsm.h"
#include "ftci.h"
#include "ftds.h"
#include "ftsr_decode.h"
#include "get_input.h"
#include "segmentation.h"
#include "suspend_resume.h"
#include "time.h"

time_t ft_session_start_time;
time_t ft_session_end_time;



void ft_save_session_start_time(void)
{
	ft_session_start_time = time(NULL);
}


void ft_save_session_end_time(void)
{
	ft_session_end_time = time(NULL);
}


time_t ft_get_session_time(void)
{
	if(ft_session_end_time > ft_session_start_time)
	{
		return (ft_session_end_time-ft_session_start_time);
	}
	else
	{
		return 0;
	}
}


/**
 *@brief State Machine :Function that handles data transmission and input collecting
 *
 */
tc_tm_id_e_ft ft_statemachine_upload(void)
{
	eSystemState currentState;
	tc_tm_id_e_ft tc_id = FT_TC_TM_MAX_ID;

  	if(tx_info.seq_loss_detect_enable != SEQ_LOSS_DETECTION_OFF)
  	{
  		ft_sus_res_handler();
  	}
 	else
 	{
 		/* packet loss detection will not work */
 	}
	ft_get_sband_link_status();
	currentState = ft_fsm_read_state();
	switch (currentState)
	{

		case FT_Init:
			//init_file_transfer();
			break;

		case FT_Idle_State:
			break;

		case FT_Send_Upload_Request:
			ftci();
			ftsr_incoming_frame_buffer_clear();
			clear_ping_request();
			ft_clear_retranmission_status();
			tc_id = FT_TC_FTCI;
			break;

		case FT_Wait_for_2sec:
			waitfor2seconds();
			break;

		case FT_Segmentation:
			segmentation();
			break;

		case FT_Sequence_Transmission:
			tc_id = ftds();
			break;

		case FT_Waitfor_FTSR:
			ftds();
			break;

		case FT_Suspended:
			break;

		case FT_Resumed:
			break;

		default:
			break;
	}

	ft_decode_ftsr_frame();

	return tc_id;
}

/**
 *@brief State Machine :Function that use to update the session id 
 *
 */
void ft_tx_session_id_update(uint8 option)
{
	if(option == FT_SESSION_ID_INC)
	{
		if(	tx_info.session_id < FT_SESSION_ID_MAX)
		{
				tx_info.session_id++;
		}
		else
		{
 	      tx_info.session_id = 1;
		}
	}
	else if(option == FT_SESSION_ID_DEC)
	{
		if(session_id > 0)
		{
		    	tx_info.session_id--;
		}
		else
		{
		}
	}
	else if(option == FT_SESSION_ID_CLR)
	{
			tx_info.session_id = 0;
	}
	else
	{
        printf("INVALID OPTION\n");
	}
}

/**
 *@brief State Machine :Function that use to read session id 
 *
 */
uint8_t ft_tx_session_id_read(void)
{
	return tx_info.session_id;
}

