/*
 *  Copyright (C) 2021 Texas Instruments Incorporated
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *    Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the
 *    distribution.
 *
 *    Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <kernel/dpl/DebugP.h>
#include "ti_drivers_config.h"
#include "ti_drivers_open_close.h"
#include "ti_board_open_close.h"
#include <kernel/dpl/HwiP.h>

/*
 * This is an empty project provided for all cores present in the device.
 * User can use this project to start their application by adding more SysConfig modules.
 *
 * This application does driver and board init and just prints the pass string on the console.
 * In case of the main core, the print is redirected to the UART console.
 * For all other cores, CCS prints are used.
 */

// ================================================================================================
// INIT OBJECT
UARTLLD_InitObject mygUartInitObject[CONFIG_UART_NUM_LLD_INSTANCES] =
{
        {
        .inputClkFreq       = 48000000,
        .baudRate           = 115200,
        .dataLength         = UART_LEN_8,
        .stopBits           = UART_STOPBITS_1,
        .parityType         = UART_PARITY_NONE,
        .readReturnMode     = UART_READ_RETURN_MODE_FULL,
        .hwFlowControl      = FALSE,
        .hwFlowControlThr   = UART_RXTRIGLVL_16,
        .transferMode       = UART_CONFIG_MODE_POLLED,
        .intrNum            = 217U,
        .intrPriority       = 4U,
        .operMode           = UART_OPER_MODE_16X,
        .rxTrigLvl          = UART_RXTRIGLVL_16,
        .txTrigLvl          = UART_RXTRIGLVL_16,
        .rxEvtNum           = 0U,
        .txEvtNum           = 0U,
        .clockP_get         = ClockP_getTicks,
        .clockP_usecToTick  = ClockP_usecToTicks,
        .writeCompleteCallbackFxn = NULL,
        .readCompleteCallbackFxn  = NULL,
        },
};

HwiP_Object myINTR_obj;

static void Emad_ISR(void *arg);

static void UART_Interrupt_Assignation(void)
{
    int32_t         status;
    HwiP_Params     hwiPrms;


    /* Register interrupt */
    HwiP_Params_init(&hwiPrms);
    hwiPrms.intNum      = gUartInitObject[0].intrNum;
    hwiPrms.priority    = gUartInitObject[0].intrPriority;
    hwiPrms.callback    = &Emad_ISR;
    hwiPrms.args        = (void *) gUartInitObject;
    status              = HwiP_construct(&myINTR_obj, &hwiPrms);
    DebugP_assert(status == SystemP_SUCCESS);

    return;
}

// ================================================================================================

uint8_t ReadBuf[8];

static void Emad_ISR(void *arg)
{
    (void) UART_lld_write(gUartHandleLld[CONFIG_UART0], "I'm In the ISR\n\r", 16, 0xFFFF, NULL);

    uint32_t       intrType;

    intrType = UART_getIntrIdentityStatus(gUartHandleLld[CONFIG_UART0]->baseAddr);

    /* Check RX FIFO threshold is set */
    // Data is present in the UART FIFO
    if((intrType & UART_INTID_RX_THRES_REACH) == UART_INTID_RX_THRES_REACH)
    {
        uint32_t       readSuccess;
        uint8_t       *readBuf, readChar;
        // uint8_t        dataCount = 8;

        // /* Read all data from RX FIFO */
        readBuf = (uint8_t *) &ReadBuf[0];
        // while(1)
        // {
        // for(uint8_t i = 0; i<8; i++)
        // {
        //     readSuccess = UART_getChar(gUartHandleLld[CONFIG_UART0]->baseAddr, &readChar);
        //     readBuf[i] = readChar; 
        // }

            // readSuccess = UART_lld_read(gUartHandleLld[CONFIG_UART0], readBuf, 8, 0xFFFF, NULL);
            
        //     if(readSuccess == SystemP_SUCCESS)
        //     {
        //         /* Store data in buffer */
        //         // Data is read successfully
                // (void) UART_lld_write(gUartHandleLld[CONFIG_UART0], readBuf, 8, 0xFFFF, NULL);

        //         break;
        //     }
        // }

        // UART_intrDisable(gUartHandleLld[CONFIG_UART0]->baseAddr, UART_INTR_RHR_CTI);

    }

    (void) UART_lld_write(gUartHandleLld[CONFIG_UART0], "I'm at the end of the ISR\n\r", 27, 0xFFFF, NULL);
    // HwiP_destruct(&myINTR_obj);


}

// ================================================================================================
void empty_main(void *args)
{
    /* Open drivers to open the UART driver for console */
    // Drivers_open();
    Board_driversOpen();

    // INIT UART
    int32_t status = UART_STATUS_SUCCESS;

    gUartHandleLld[CONFIG_UART0]             = &gUartObject[CONFIG_UART0];
    gUartHandleLld[CONFIG_UART0]->state      = UART_STATE_RESET;
    gUartHandleLld[CONFIG_UART0]->baseAddr   = CSL_MCU_UART0_BASE;
    gUartHandleLld[CONFIG_UART0]->hUartInit = &mygUartInitObject[CONFIG_UART0];

    status += UART_lld_init(gUartHandleLld[CONFIG_UART0]);

    DebugP_assert(status == UART_STATUS_SUCCESS);

    // Let's Get to Business
    // Assign the Interrupt
    UART_Interrupt_Assignation();
    
    // Enable Reception Interrupt
    UART_intrEnable(gUartHandleLld[CONFIG_UART0]->baseAddr, UART_INTR_RHR_CTI);

    while(1){}

    Board_driversClose();
    Drivers_close();
}
