#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

#include "ospTypes.h"
#include "ospFile.h"


int32_t osp_file_init(file_t *file)
{
    pthread_mutex_init(&file->mutex, NULL);
    return 1;
}

int32_t osp_file_read_tmp(char *buffer, int32_t size, file_t *file)
{
    int32_t fd = open(file->filepath, O_RDONLY);
    if (fd < 0)
    {
        printf(" file open failure \n");
        return -1;
    }
    
    int32_t result = read(fd, buffer, size);
    if ((result > size) || (result < -1))
    {
        printf(" file read failure \n");
        close(fd);
        return -1;
    }
    
    close(fd);
    return result;
}

int32_t osp_file_read(char *buffer, int32_t size, file_t *file)
{
    //pthread_mutex_lock(&file->mutex);
    int32_t result = osp_file_read_tmp(buffer, size, file);
    //pthread_mutex_unlock(&file->mutex);
    return result;
}

int32_t osp_file_write_tmp(file_t *file, char *buffer, int32_t size)
{
    int32_t fd = open(file->filepath, file->flag, file->mode);
    if (fd < 0)
    {
        printf(" file open failure  \n");
        return -1;
    }
    
    int32_t result = write(fd, buffer, size);
    if (result < -1)
    {
        printf(" file write failure  \n");
        close(fd);
        return -1;
    }
    
    fsync(fd);
    close(fd);
    return result;
}

int32_t osp_file_write(file_t *file, char *buffer, int32_t size)
{
    pthread_mutex_lock(&file->mutex);
    int32_t result = osp_file_write_tmp(file, buffer, size);
    pthread_mutex_unlock(&file->mutex);
    return result;
}

int32_t osp_mkdirs(char *path, mode_t mode) 
{
    char str[512];
    strncpy(str, path, 512);
    int32_t len = strlen(str);
    int32_t i;
    struct stat s;


    for (i = 0; i < len; i++)
    {
        if (str[i] == '/')
        {
            str[i] = '\0';
            if (access(str, 0) != 0)
            {
                mkdir(str, mode);
            }
            str[i] = '/';
        }
    }
    if (len > 0 && access(str,0) != 0)
    {
        mkdir(str, mode);
    }
    stat(path, &s);
    if (S_ISDIR(s.st_mode))
         return 0;
    return 0;
}

int32_t osp_file_is_exist(char *file)
{
    int32_t ret;

    ret = access(file, F_OK);
    if (0 == ret)
    {
        ret = 1;
    }
    else
    {
        ret = 0;
    }

    return ret;
}
int32_t osp_get_file_path(char *name, char *path)
{
    int32_t i;
    int32_t len;

    if ((NULL == name) || (NULL == path))
    {
        return -1;
    }
    
    len = strlen(name);
    
    for (i = len-1; i >= 0; i--)
    {
            if (name[i] == '/')
            {
                break;
            }
    }

    memcpy(path, name, i);

    return 0;
    
}

