/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include "iotcs_port_mutex.h"
#include "mbed.h"
#include "rtos.h"

#include "log/log.h"
#define IOTCSP_MODULE_LOG_CHANNEL LOG_CHANNEL_PORT_MUTEX
#include "log/log_template.h"

iotcs_port_mutex iotcs_port_mutex_create(void) {

    Mutex *mutex = new Mutex();
    return mutex;
}

void iotcs_port_mutex_destroy(iotcs_port_mutex mutex) {

    delete reinterpret_cast<Mutex*> (mutex);
    return;
}

void iotcs_port_mutex_lock(iotcs_port_mutex mutex) {
    osStatus ret;
    do {
        ret = (reinterpret_cast<Mutex*> (mutex))->lock(osWaitForever);
        if (ret != 0) {
            LOG_CRIT("Mutex Lock Error message: %d", ret);
        }
    } while (ret == osErrorTimeoutResource);
}

void iotcs_port_mutex_unlock(iotcs_port_mutex mutex) {
    osStatus ret;
    do {
        ret = (reinterpret_cast<Mutex*> (mutex))->unlock();
        if (ret != 0) {
            LOG_CRIT("Mutex Unlock Error message: %d", ret);
        }
    } while (ret == osErrorTimeoutResource);
}