#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "VirtualFloppy.h"
#include "Fat12FileSystem.h"

using namespace FatFS;

int main(int argc, char *argv[])
{
    if (argc < 4)
    {
        printf("usage: FAT12.exe isoImage comand [option|file|directory|\n");
        printf("command: read, ls, cp\n");
        return 1;
    }

    const char* fdImage  = argv[1];
    const char* command  = argv[2];
    const char* arg1     = argv[3];
    const char* arg2     = argc >= 4 ? argv[4] : NULL;

    /* initialize device */
    FILE* fp = fopen(fdImage, "rb");

    if (fp == NULL)
    {
        printf("file %s can not read\n", fdImage);
        return 1;
    }

    IStorageDevice* flp = new VirtualFloppy(fp);

    Fat12FileSystem* fs = new Fat12FileSystem(flp);

    if (!fs->Initialize())
    {
        printf("Initialize Error = %d\n", fs->GetLastError());
        delete fs;
        delete flp;
        fclose(fp);
        return 1;
    }

    if (strcmp(command, "read") == 0)
    {
        printf("read : not implemented yet!\n");
    }
    else if (strcmp(command, "cp") == 0)
    {
        printf("cp : not implemented yet!\n");
    }
    else if (strcmp(command, "ls") == 0 && strcmp(arg1, "-l") == 0)
    {
        _A<FileSystemEntry*> files = fs->GetFileSystemEntries(arg2);

        char* month[] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

        FOREACH (FileSystemEntry*, file, files)
        {
            FileDate* date = file->GetCreateDate();

            printf("%d %s %d %d %d:%d:%d %s%s\n"
                   , file->IsDirectory() ? 0 : file->GetSize()
                   , month[date->GetMonth()]
                   , date->GetDay()
                   , date->GetYear()
                   , date->GetHour()
                   , date->GetMinute()
                   , date->GetSecond()
                   , (const char*)file->GetName()
                   , file->IsDirectory() ? "/" : "");
        }
        END_FOREACH
    }
    else if (strcmp(command, "ls") == 0)
    {
        _A<FileSystemEntry*> files = fs->GetFileSystemEntries(arg1);

        FOREACH (FileSystemEntry*, file, files)
        {
            printf("%s\n", (const char*)file->GetName());
        }
        END_FOREACH
    }
    else
    {
        printf("command %s not supported\n", command);
    }

    delete fs;
    delete flp;
    fclose(fp);

    return 0;


    return 0;
}
