//#DOC Main, program entry and main loop
#include "main.h"
#include <otSerial.h>
#include <otTimer.h>
#include <otMalloc.h>
#include <otPrintf.h>
#include <otSerialThread.h>
#include <otCommandParser.h>
#include <otLegacyCommand.h>
#include <otFILE.h>

#define PARSER_MAX_AVAILABLE_COMMANDS   128

otCommandParser parser;
otFILE          file;
otSerialThread  io;

FAST_CODE_2 U8 _getChar()
{
    printf("\nPress . or ESC to stop display or any other key to continue\n");
    return io.waitChar();
}

void commandLineInterpreter()
{
    U8  commandLine[256];
    
    if(io.getString(commandLine, 256))
        switch(parser.parse((char *) commandLine))
        {
            case 1: printf("\nBatch exists but is empty: [%s]\n", commandLine);
                    break;
            case 2: printf("\nBatch don't exists: [%s]\n", commandLine);
                    break;
            case 3: printf("\nUnknown command: [%s]\n", commandLine);
                    break;
            case 4: printf("\n???\n");
                    break;
            case 5: // Syntax error
                    break;
        }
    otLegacyDisplayPrompt();
}

void setup()
{
    // printf output is now directed on UART0
    setStdout(4096, UART0);
    
    DelayMs(1000);
    
    // Init UART0 handler
    io.init(UART0, 115200);
    
    if(file.init())
    {
        file.setStdin(_getChar);
        file.setStdout(printf);
        // If SD is present and ready
        parser.init(PARSER_MAX_AVAILABLE_COMMANDS, &file);
        otLegacyCommandsInit(&parser, &io, &file);
    }
    else
    {
        parser.init(PARSER_MAX_AVAILABLE_COMMANDS);
        otLegacyCommandsInit(&parser, &io);
    }
    otLegacyDisplayPrompt();
}

void loop()
{
    
    /*
    U8  dstBuffer[32];
    printf("Wait a string\n");
    if(io.getString(dstBuffer, 32, 20000))
        printf("[%s]\n", dstBuffer);
    else
        printf("timeout\n");
    
    printf("Wait a character\n");
    U8 ch = io.waitChar();
    printf("Character = %X\n", ch);
    */
    
    commandLineInterpreter();
}