// File: src/AutomataMiner.sol



//SPDX-License-Identifier: MIT
pragma solidity^0.8.20.0;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/IAutomataMiner.sol";

/*
  Automata Miner Contract
  Fixed rate APR
  Auto compound feature
  Airdrop feature
*/

contract AutomataMiner is ReentrancyGuard, Ownable {
  uint256 dailyAPR = 9;
  uint256 referralBonus = 12;
  uint256 devFee = 5;
  uint256 public totalSupply;
  address public treasuryAddress;
  uint256 public totalClaimed;

  mapping(address => User) public user;

  constructor(address treasuryAddress_) Ownable(msg.sender) payable {
    treasuryAddress = treasuryAddress_;
  }

  function setReferral(address account_, address referral_) public onlyOwner {
    user[account_].referral = referral_;
  }

  function setDailyApr(uint256 dailyApr_) public onlyOwner {
    dailyAPR = dailyApr_;
  }

  function setReferralBonus(uint256 referralBonus_) public onlyOwner {
    referralBonus = referralBonus_;
  }

  function setDevFee(uint256 devFee_) public onlyOwner {
    devFee = devFee_;
  }

  function setTreasuryAddress(address treasuryAddress_) public onlyOwner {
    treasuryAddress = treasuryAddress_;
  }

  function toggleAutoCompound() public {
    User storage user_ = user[msg.sender];
    _compoundUser(user_);
    user_.autoCompound = !user_.autoCompound;
  }

  function airdropTokens(
        address[] memory addresses,
        uint256 _amount
    ) public onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            user[addresses[i]].tokens = user[addresses[i]].tokens + _amount;
        }

        totalSupply += (_amount * addresses.length);
    }

  function compound() public {
    _compoundUser(user[msg.sender]);
  }

  function _compoundUser(User storage user_) internal {
    // uint256 currentTime = (block.timestamp - user_.lastClaim) / 1 days;
    // uint256 remainingTime = (block.timestamp - user_.lastClaim) % 1 days;

    // uint256 fullCompound;
    // if(currentTime > 0) {
    //   fullCompound = user_.tokens * dailyAPR / 100;
    // }
    // if(currentTime > 1) {
    //   for(int i = currentTime-1; i>currentTime; i--) {
    //     fullCompound = fullCompound * dailyAPR / 100;
    //   }
    // }
    
    // uint256 halfCompound = (user_.tokens + fullCompound) * partialAPR * remainingTime / 1 days / 100;
    // uint256 newTokens = fullCompound + halfCompound + user_.referralBonus;
    uint256 timeDelta = (block.timestamp - user_.lastClaim) * 100000 / 1 days;
    uint256 newTokens = user_.tokens * dailyAPR * timeDelta / 100000 / 100 + user_.referralBonus;
    
    if(user_.referral != address(0)) {
      user[user_.referral].referralBonus += newTokens * referralBonus / 100;
    }
    totalSupply += newTokens;
    user_.referralBonus = 0;
    user_.tokens += newTokens;
    user_.lastClaim = block.timestamp;
  }

  function buyTokens(address referral_) public payable nonReentrant {
    User storage user_ = user[msg.sender];
    if(user_.tokens == 0) {
      user_.autoCompound = true;
    }

    if(user_.referral == address(0)) {
      require(referral_ != msg.sender);
      user_.referral = referral_;
    }

    _compoundUser(user_);
    user_.tokens += msg.value;
    totalSupply += msg.value;
    uint256 fee = msg.value * devFee / 100;
    (bool success,) = payable(treasuryAddress).call{value: fee}("");
    require(success);
  }

  function claimTokens(bool reenable) public nonReentrant {
    User storage user_ = user[msg.sender];
    require(!user_.autoCompound, "auto compound must be disabled");
    require(user_.cooldown < block.timestamp, "account in cooldown");
    uint256 timeDelta = (block.timestamp - user_.lastClaim) * 100000 / 1 days;
    uint256 newTokens = user_.tokens * dailyAPR * timeDelta / 100000 / 100 + user_.referralBonus;

    user[user_.referral].referralBonus += newTokens * referralBonus / 100;
    uint256 totalPayout = calculateExchange(newTokens, totalSupply, address(this).balance);
    totalSupply += newTokens;
    uint256 fee = totalPayout * devFee / 100;
    uint256 payout = totalPayout - fee;
    user_.totalClaimed = payout;
    totalClaimed += payout;

    user_.cooldown = block.timestamp + 12 hours;

    if(reenable) {
      user_.autoCompound = reenable;
    }
    
    bool success;
    (success,) = payable(treasuryAddress).call{value: fee}("");
    require(success);
    (success,) = payable(msg.sender).call{value: payout}("");
    require(success);
  }

  function calculateClaim(address account_) public view returns(uint256) {
    User storage user_ = user[account_];
    uint256 timeDelta = (block.timestamp - user_.lastClaim) * 100000 / 1 days;
    uint256 newTokens = user_.tokens * dailyAPR * timeDelta / 100000 /100 + user_.referralBonus;

    uint256 totalPayout = calculateExchange(newTokens, totalSupply + newTokens, address(this).balance);
    uint256 fee = totalPayout * devFee / 100;
    return totalPayout - fee;
  }

  function calculateCompound(address account_) public view returns(uint256) {
    User storage user_ = user[account_];
    uint256 timeDelta = (block.timestamp - user_.lastClaim) * 100000 / 1 days;
    return user_.tokens * dailyAPR * timeDelta / 100000 / 100 + user_.referralBonus;
  }

  function calculateExchange(
    uint256 rt,
    uint256 rs,
    uint256 bs
  ) public pure returns (uint256) {
    return (10000 * bs) / (5000 + ((10000 * rs + 10000 * rt) / rt));
  }

  function withdraw(uint256 amount) public onlyOwner {
    require(address(this).balance >= amount);
    payable(owner()).call{value: amount}("");
  }
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

// File: src/interfaces/IAutomataMiner.sol



//SPDX-License-Identifier: MIT
pragma solidity^0.8.20.0;

struct User {
  uint256 tokens;
  uint256 referralBonus;
  uint256 lastClaim;
  uint256 totalClaimed;
  uint256 cooldown;
  bool autoCompound;
  address referral;
}
// File: lib/openzeppelin-contracts/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}