/*
 * Go2Log.c
 * 
 * Gocator system communication library
 * Copyright (C) 2010 by LMI Technologies Inc.
 * 
 * Licensed under The MIT License.
 * Redistributions of files must retain the above copyright notice.
 */
#include <z/zGo2Log.h>
#include <z/zGo2Health.h>
#include <z/zGo2Data.h>
#include <z/zGo2Api.h>

GO2_EXPORT(Go2Status) Go2Log_Construct(Go2Log* log, const Go2Char* path, Go2Bool read)
{
    Go2Log output = zNIL; 
    Go2Status status = GO2_OK; 

    zCHECK(zCalloc(&output, 1, sizeof(Go2LogClass))); 

    if (!zSUCCESS(status = Go2Log_Init(output, path, read)))
    {
        zCHECK(Go2Object_Destroy(output)); 
        return status; 
    }
    
    *log = output; 

    return GO2_OK; 
}

GO2_EXPORT(Go2Status) Go2Log_Destroy(Go2Log log)
{
    return Go2Object_Destroy(log); 
}

GO2_EXPORT(Go2Status) Go2Log_Init(Go2Log log, const Go2Char* path, Go2Bool read)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);

    zCHECK(Go2Object_Init(log, GO2_TYPE_LOG));

    obj->Release = Go2Log_VRelease;

    zCHECK(zFile_Construct(&obj->stream, path, (read) ? zFILE_MODE_READ : zFILE_MODE_WRITE)); 
    zCHECK(zSerializer_Construct(&obj->serializer, zFile_Read, zFile_Write, obj->stream)); 
   
    return GO2_OK; 
}

GO2_EXPORT(Go2Status) Go2Log_VRelease(Go2Log log)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);

    zCHECK(zSerializer_Destroy(obj->serializer)); 
    zCHECK(zFile_Destroy(obj->stream)); 

    zCHECK(Go2Object_VRelease(log));  
        
    return GO2_OK; 
}

GO2_EXPORT(Go2Status) Go2Log_Write(Go2Log log, Go2Object message)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);

    switch (Go2Object_Type(message))
    {
    case GO2_TYPE_HEALTH:       return zResult_Write(Go2Health_Result(message), obj->serializer); 
    case GO2_TYPE_DATA:         return zResult_Write(Go2Data_Result(message), obj->serializer); 
    default:                    return GO2_ERROR_PARAMETER; 
    }
}

GO2_EXPORT(Go2Status) Go2Log_Read(Go2Log log, Go2Object* message)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);
    zResult result = zNIL; 
    
    zCHECK(zResult_Read(&result, obj->serializer)); 

    switch (zResult_Id(result))
    {
    case GO2_HEALTH_MESSAGE_ID:
        return Go2Health_Construct(message, result);     
    case GO2_DATA_MESSAGE_ID:
        return Go2Data_Construct(message, result); 
    default:
        zCHECK(zResult_Destroy(result)); 
        return zERROR_STREAM; 
    }
}

GO2_EXPORT(Go2UInt64) Go2Log_Position(Go2Log log)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);
    return zFile_Position(obj->stream); 
}

GO2_EXPORT(Go2UInt64) Go2Log_Length(Go2Log log)
{
    Go2LogClass* obj = zHANDLE_POINTER(log);
    return zFile_Length(obj->stream); 
}
