#include "SDCardMgr.h"
#include "sd_hw_ctl.h"
#include "FileSystem/fileio_lfn.h"
#include <stdio.h>
#include "timer.h"

int mSDCardState;
int mCardDetected;
int mCardMounted;
uint16_t mDriveLetter;


void FILEIO_GetTimestamp (FILEIO_TIMESTAMP * timeStamp)
{
    timeStamp->date.bitfield.day = 6;
    timeStamp->date.bitfield.month = 5;
    timeStamp->date.bitfield.year = (2017 - 1980);
    
    timeStamp->time.bitfield.hours = 9;
    timeStamp->time.bitfield.minutes = 5;
    timeStamp->time.bitfield.secondsDiv2 = 0;
    
    timeStamp->timeMs = 0;
            
}

int InitSDCard()
{
    SD_SPIConfigurePins();
    FILEIO_Initialize();
    mSDCardState = SD_CARD_INIT_STATE;
    
    mCardDetected = 0;
    mCardMounted = 0;
    
    mDriveLetter = 'D';
    TimerStart(SD_CARD_DETECT_TIMER,5000);

    return 1;
}

int TickSDCard()
{
    switch(mSDCardState)
    {
        case SD_CARD_INIT_STATE:
        {
            if(IsTimerExpired(SD_CARD_DETECT_TIMER))
            {
                if(FILEIO_MediaDetect(0, 0) == true)
                {
                    mCardDetected = 1;
                    mSDCardState = SD_CARD_MOUNT_DRIVE_STATE;
                    printf("SD Card detected\n");
                }
                else
                {
                    TimerStart(SD_CARD_DETECT_TIMER,999);
                }
            }
            break;
        }
        case SD_CARD_MOUNT_DRIVE_STATE:
        {
            if(FILEIO_DriveMount(mDriveLetter, 0, 0) == FILEIO_ERROR_NONE)
            {
                mCardMounted = 1;
                mSDCardState = SD_CARD_READY_STATE;
                printf("SD Card mounted on drive %c\n",(unsigned char)mDriveLetter);
            }
            else
            {
                mSDCardState = SD_CARD_ERROR_MOUNTING_STATE;
                printf("Error mounting SD card.\n");
            }
            break;
        }
        case SD_CARD_READY_STATE:
        {
//            if(FILEIO_MediaDetect(0, 0) == false)
//            {
//                mCardDetected = 0;
//                mSDCardState = SD_CARD_INIT_STATE;
//            }
            break;
        }
        case SD_CARD_ERROR_MOUNTING_STATE:
        {
            //wait for removal of the sd card...
//            if(FILEIO_MediaDetect(0, 0) == false)
//            {
//                mCardDetected = 0;
//                mSDCardState = SD_CARD_INIT_STATE;
//                printf("SD Card removed");
//            }
            break;
        }
    }
    
}

int MountDrive()
{
    
}

int IsDriveDetected()
{
    return mCardDetected;
}

int IsDriveMounted()
{
    return mCardMounted;
}

