/*
 * oclh_h_base_log.с
 *      Author: havock
 */
#include <stdlib.h>
#include <oclh_h_base_log.h>

_GHT_LOG _ghf_declLog(void) {
    _GHT_LOG log={ .pfOut=NULL, .pMtx=NULL };
    return(log);
}

int32_t _ghf_genrLog(_GHT_LOG* const pLog, const char* const pcFileName) {
    FILE*           pFile=NULL;
    pthread_mutex_t EmptyMtx=PTHREAD_MUTEX_INITIALIZER,
                    *pMtx=NULL ;
    _ghf_wipeLog(pLog);
    if(pcFileName) {
        pFile=fopen(pcFileName,"w");
        if(!pFile) { perror(""); return(_GHM_OPEN_FILE_ERROR); }
    } else pFile=stdout;
    pMtx=malloc(sizeof(pthread_mutex_t));
    if(!pMtx) { fclose(pFile); perror(""); return(_GHM_HOST_MEMALLOC_ERROR); }
    *pMtx=EmptyMtx;
    pLog->pfOut=pFile;
    pLog->pMtx=pMtx;
    return(_GHM_OK);
}

int32_t _ghf_isLog_Valid(const _GHT_LOG Log) {
    return(Log.pMtx && Log.pfOut);
}

int32_t _ghf_wipeLog(_GHT_LOG* const pLog) {
    if(pLog) {
        if(pLog->pMtx) {
            pthread_mutex_lock(pLog->pMtx);
            if(pLog->pfOut && pLog->pfOut!=stdout) fclose(pLog->pfOut);
            pLog->pfOut=NULL;
            pthread_mutex_unlock(pLog->pMtx);
        } else {
            if(pLog->pfOut && pLog->pfOut!=stdout) fclose(pLog->pfOut);
            pLog->pfOut=NULL;
        }
        if(pLog->pMtx) { free(pLog->pMtx); pLog->pMtx=NULL; }
        pLog->pMtx=NULL;
    }
    return(_GHM_OK);
}
