/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */

/*
 * ----------------------------------------------------------------------------------
 * The code in this file is copied (with a slight modifications) from:
 *     Esp.cpp - esp8266-specific APIs
 * ----------------------------------------------------------------------------------
 * Copyright (C) 2015 Ivan Grokhotkov. All rights reserved.
 *
 * This file is part of the esp8266 core for Arduino environment.
 *
 * This code was influenced by NodeMCU and Sming libraries, and first version of
 * Arduino wrapper written by Hristo Gochkov.
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 * ----------------------------------------------------------------------------------
 */


#include "CoreLib.h"
#include "CoreUtil.h"


namespace eCxx {

namespace NodeMCU {


extern uint8_t* random(uint8_t* resultArray, const size_t outputSizeBytes)
{
    constexpr uint8_t cooldownMicros = 2;

    static uint32_t lastCalledMicros = micros() - cooldownMicros;

    uint32_t randomNumber = 0;

    for(size_t byteIndex = 0; byteIndex < outputSizeBytes; ++byteIndex) {
        if(byteIndex % 4 == 0) {
            // Old random number has been used up (random number could be exactly 0, so we can't check for that)

            const uint32_t timeSinceLastCall = micros() - lastCalledMicros;
            if(timeSinceLastCall < cooldownMicros) delayMicroseconds(cooldownMicros - timeSinceLastCall);

            randomNumber     = RANDOM_REG32;
            lastCalledMicros = micros();
        }

        resultArray[byteIndex]  = randomNumber;
        randomNumber           >>= 8;
    }

    return resultArray;
}


extern uint32_t random()
{
    union {
        uint32_t b32;
        uint8_t  b8[4];

    } result;

    random(result.b8, 4);

    return result.b32;
}


} // namespace NodeMCU

} // namespace eCxx
