#pragma GCC diagnostic error "-Wall"

#include "cli.h"
#include <string.h>
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#include "CLI_Commands.h"
#include "settings_api.h"
#include "parameters.h"
#include "control_symbol.h"
#include "log.h"
#include "web_params_api.h"
#include "tinystdio.h"
#include "telnet_server.h"

#define ISO_nl       0x0a
#define ISO_cr       0x0d
#define ISO_etx      0x03
#define ISO_del      0x7f

#define REPEAT_SENSOR_INFO_TIME		configTICK_RATE_HZ*5*1

/**
  * @brief  Общая структура настроек
  */
extern SETTINGS_t sSettings;

static const char * const pcEndOfCommandOutputString = "\r\n[Нажмите клавишу ENTER для повторного выполнения предыдущей команды]\r\n>";
const char pcWarningMessage[] = "Количество соединенений превышено. Данное соединение будет закрыто\r\n";
const unsigned pcWarningMessageLen = array_len(pcWarningMessage);
extern int8_t cOutputBuffer[ configCOMMAND_INT_MAX_OUTPUT_SIZE ];
cli_state_t cli_states[MAX_SESSIONS];

void SensorInfoTimerCallback(TimerHandle_t pxTimer) {
	portBASE_TYPE xReturned = pdTRUE;
	uint8_t num_timer = 0;
	for (uint8_t i = 0; i < array_len(cli_states); i ++) {
		if(pxTimer == cli_states[i].RepeatSensorInfoTimer){
			num_timer = i;
			break;
		}
	}
	do {
		/* Ensure there is not a string lingering in
		the output buffer. */
		cOutputBuffer[ 0 ] = 0x00;
		xReturned = FreeRTOS_CLIProcessCommand(&cli_states[num_timer], (int8_t *)"sensor info", cOutputBuffer, configCOMMAND_INT_MAX_OUTPUT_SIZE);
		cli_states[num_timer].send(cli_states[num_timer].num_connect, (char *)cOutputBuffer, strlen( ( const char * ) cOutputBuffer ));

	} while( xReturned != pdFALSE );
	xTimerStart(cli_states[num_timer].RepeatSensorInfoTimer, 0);
}

static char *get_user_name(user_level_t user_id)
{
	char *username;
	switch (user_id) {
		case 0:
			username = "Администратор";
			break;
		case 1:
			username = "Пользователь";
			break;
		default:
			username = "Неизвестен";
			break;
	}
	return username;
}

static void FreeRTOS_ChangePWDProcess( int8_t * pcWriteBuffer, cli_state_t *s)
{
	static char password[MAX_WEB_PASSWD_LEN];	// trading reentrancy for memory
	const int8_t * const pcNewPSWHeader = ( int8_t * ) "\r\nВведите повторно новый пароль:";

	memset(pcWriteBuffer, 0, configCOMMAND_INT_MAX_OUTPUT_SIZE);

	uint32_t len = strlen(s->buf);
	if (len >= MAX_WEB_PASSWD_LEN) {
		strcpy((char *)pcWriteBuffer, "\r\nНовый пароль слишком длинный!\r\n>");
		s->input_state = CLI_CMD;
		return;
	}

	if(s->input_state == CLI_CHANGE_PWD){
		memset(password, 0, MAX_WEB_PASSWD_LEN);
		if(!control_string_en_digit(s->buf, len)){
			strcpy( ( char * ) pcWriteBuffer, "\r\nОшибка при вводе нового пароля\r\n>" );
			s->input_state = CLI_CMD;
		} else {
			strncpy(password, s->buf, len);
			strncpy( ( char * ) pcWriteBuffer, ( const char * ) pcNewPSWHeader, strlen( ( char * ) pcNewPSWHeader ) );
			s->input_state = CLI_CHANGE_PWD_ACK;
		}
	} else {
		if (strncmp(password, s->buf, MAX_WEB_PASSWD_LEN) == 0) {
			memcpy(sSettings.sAuth[s->id_change_pwd].password, password, 11);
			cli_save_config(s);
			log_event_data(LOG_PSW_CHANGE, get_user_name(s->user_id));
			strcpy( ( char * ) pcWriteBuffer, "\r\nПароль успешно изменен\r\n>" );
		} else {
			strcpy( ( char * ) pcWriteBuffer, "\r\nОшибка при вводе нового пароля\r\n>" );
		}
		s->input_state = CLI_CMD;
	}
}


static void cli_input(cli_state_t *s)
{
	portBASE_TYPE xReturned;

	switch(s->input_state){
		case CLI_AUTH:
		case CLI_AUTH_PASSW:
			if(FreeRTOS_CLIAuthProcess(cOutputBuffer, s)){
				s->send(s->num_connect, (char *)cOutputBuffer, strlen( ( const char * ) cOutputBuffer ));
				memset( s->buf, 0x00, cmdMAX_INPUT_SIZE );
			}
			else{
				s->state = STATE_CLOSE;
			}
			break;
		case CLI_CMD:
			/* The input string has been terminated.	Was the
			input a quit command? */
			if( strcmp( "quit", ( const char * ) s->buf ) == 0 )
			{
				s->state = STATE_CLOSE;
			}
			else
			{
				/* The input string was not a quit command.
				Pass the string to the command interpreter. */

				/* See if the command is empty, indicating that the last command is
				to be executed again. */
				if( s->bufptr == 0 )
				{
					if(s->flag_telnet_ip_option ){
						s->flag_telnet_ip_option = false;
						return;
					}
					else{
						strcpy( s->buf, s->prev_cmd );
					}
				}

				/* Transmit a line separator, just to make the
				output easier to read. */
				s->send(s->num_connect, "\r\n", strlen( "\r\n" ));

				do
				{
					/* Ensure there is not a string lingering in
					the output buffer. */
					cOutputBuffer[ 0 ] = 0x00;
					// FIXME telnetState should go into the command processor
					//input_state = s->input_state;
					xReturned = FreeRTOS_CLIProcessCommand(s, (int8_t *)s->buf, (int8_t *)cOutputBuffer, configCOMMAND_INT_MAX_OUTPUT_SIZE );
					//s->input_state = input_state;
					s->send(s->num_connect, (char *)cOutputBuffer, strlen( ( const char * ) cOutputBuffer ));

				} while( xReturned != pdFALSE );

				if( strcmp( "sensor info", ( const char * ) s->buf ) == 0 ){
					strcpy( s->prev_cmd, s->buf );
					memset( s->buf, 0x00, cmdMAX_INPUT_SIZE );
					xTimerStart(s->RepeatSensorInfoTimer, 0);
				} else {
					/* All the strings generated by the input
					command have been sent.	Clear the input
					string ready to receive the next command.
					Remember the command that was just processed
					first in case it is to be processed again. */
					strcpy( s->prev_cmd, s->buf );
					memset( s->buf, 0x00, cmdMAX_INPUT_SIZE );
					if(s->input_state != CLI_CHANGE_PWD)
						s->send(s->num_connect, (char *)pcEndOfCommandOutputString, strlen( ( const char * ) pcEndOfCommandOutputString ));
				}
			}
			break;
		case CLI_CHANGE_PWD:
		case CLI_CHANGE_PWD_ACK:
			FreeRTOS_ChangePWDProcess(cOutputBuffer, s);
			s->send(s->num_connect, (char *)cOutputBuffer, strlen( ( const char * ) cOutputBuffer ));
			memset( s->buf, 0x00, cmdMAX_INPUT_SIZE );
			break;

	}
}

void cli_getchar(cli_state_t *s, char incoming_char, bool echo_enabled)
{
	s->buf[s->bufptr] = incoming_char;

	if(echo_enabled && s->input_state != CLI_AUTH_PASSW){
		if (s->buf[s->bufptr] != ISO_etx && s->buf[s->bufptr] != ISO_del) {
			s->send( s->num_connect, &s->buf[s->bufptr], 1);
		}
	}
	else if(s->input_state == CLI_AUTH_PASSW){
		s->send( s->num_connect, " ", 1);
	}


	if(s->buf[s->bufptr] == ISO_nl || s->buf[s->bufptr] == 0) {
		s->bufptr = 0;
		return;
	}

	if(s->buf[s->bufptr] == ISO_cr || s->bufptr == sizeof(s->buf) - 1) {
		if(s->bufptr > 0) {
			s->buf[s->bufptr] = 0;
		}
		cli_input(s);
		s->bufptr = 0;
	} else if ( s->buf[s->bufptr] == '\b' || s->buf[s->bufptr] == ISO_del) {
		/* Backspace was pressed. Erase the last character in the string - if any. */
		s->buf[s->bufptr] = '\0';
		if (s->bufptr > 0) {
			s->bufptr--;
			s->buf[s->bufptr] = '\0';
			const char backspace[] = "\b \b";
			s->send(s->num_connect, backspace, sizeof(backspace));
		}
	} else if (s->buf[s->bufptr] == ISO_etx){
		xTimerStop(s->RepeatSensorInfoTimer, 0);
		s->flag_telnet_ip_option = true;
		if(s->input_state != CLI_CHANGE_PWD && s->input_state != CLI_CHANGE_PWD_ACK)
			s->send( s->num_connect, pcEndOfCommandOutputString, strlen( ( const char * ) pcEndOfCommandOutputString ));
	} else {
		++s->bufptr;
	}
}

void cli_init(void)
{
	for (unsigned i = 0; i < array_len(cli_states); i++) {
		memset(cli_states[i].buf, 0, cmdMAX_INPUT_SIZE);
		memset(cli_states[i].prev_cmd, 0, cmdMAX_INPUT_SIZE);
		cli_states[i].optlen = 0;
		cli_states[i].num_connect = 0;
		cli_states[i].user_id = USER;
		cli_states[i].flag_telnet_ip_option = false;
		cli_states[i].RepeatSensorInfoTimer = xTimerCreate("SensorInfoTmr", REPEAT_SENSOR_INFO_TIME, pdFALSE, ( void * ) i, SensorInfoTimerCallback);
	}
	vRegisterCLICommands();
}

cli_state_t *alloc_state(void)
{
	for (unsigned i = 0; i < array_len(cli_states); ++i) {
		if (cli_states[i].state == STATE_UNUSED) {
			cli_states[i].state = STATE_CLOSE;
			cli_states[i].prev_cmd[0] = 0;	// don't leak the previous user's history
			cli_states[i].input_state = CLI_AUTH;	// pre-authenticated state
			cli_states[i].user_id = USER;	// lowest permission level
			return &cli_states[i];
		}
	}
	return 0;
}

void free_state(cli_state_t *state)
{
	xTimerStop(state->RepeatSensorInfoTimer, 0);
	state->state = STATE_UNUSED;
}

void cli_hello(cli_state_t *cli_state)
{
	cli_state->state = STATE_NORMAL;

	const char hello[] = "hello\r\n>";
	cli_state->send(cli_state->num_connect, hello, sizeof(hello));
}

void cli_save_config(cli_state_t *cli_state)
{
	SETTINGS_Save();

	log_event_data(LOG_SETTING_SAVE, get_user_name(cli_state->user_id));
}

user_level_t cli_auth_user(const char *user, const char *password, log_type_t log_entry_type)
{
	user_level_t rv = MAX_USER_LEVELS;
	char WebPassword[MAX_WEB_PASSWD_LEN];
	char WebLogin[MAX_WEB_LOGIN_LEN];
	uint8_t valueLen, user_id;
	for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
		GetUserLogin(user_id, WebLogin, &valueLen);
		GetUserPassword(user_id, WebPassword, &valueLen);

		/* Check login and password */
		if ((strncmp(WebLogin, user, MAX_WEB_LOGIN_LEN) == 0) &&
			(strncmp(WebPassword, password, MAX_WEB_PASSWD_LEN) == 0)) {

			/* Login and pass are valid */
			rv = user_id;
			log_event_data(log_entry_type, get_user_name(user_id));
			break;
		}
	}
	return rv;
}
