// File: StakingManager.sol



// SPDX-License-Identifier: MIT
// StakingManager 
pragma solidity 0.8.21;

import "Ownable.sol";
import "TransferHelper.sol";
import "IDepositModel.sol";
import "ISandbox1.sol";


contract StakingManager is  Ownable {

    struct DepositModel {
        uint256 validAfter;
        uint256 notValidAfter;
        address modelAddress;
    }


    address public immutable stakedToken;
    address public immutable rewardMintAddress;

    DepositModel[] public depositModels;


    mapping(address => Deposit[]) public deposits;
    event DepositModelChanged(address Model, uint256 ValidAfter, uint256 NotValidAfer);
    event DepositNew(address indexed User , uint256 indexed DepositIndex, uint256 DepositValue);

    constructor(address _erc20, address _rewardMintAddress) {
        require(_erc20 != address(0), "Cant be zero address");
        stakedToken = _erc20;
        rewardMintAddress = _rewardMintAddress;
        
    }

    function deposit(Deposit memory _newDeposit) external {
        require(_newDeposit.depositModelIndex < depositModels.length, "Model with this index not exist yet");
        require(depositModels[_newDeposit.depositModelIndex].validAfter <= block.timestamp, "Model not valid yet");
        require(depositModels[_newDeposit.depositModelIndex].notValidAfter >= block.timestamp, "Model not valid already");
        // Pre Check
        bool isOK;
        (isOK, _newDeposit) = IDepositModel(depositModels[_newDeposit.depositModelIndex].modelAddress).checkOpen(
            msg.sender, 
            _newDeposit
        );

        // Save stake(depost) info
        if (isOK){
            Deposit storage d = deposits[msg.sender].push(); 
            _insertNewDepositInfo(d, _newDeposit);
            emit DepositNew(msg.sender,deposits[msg.sender].length - 1, d.body); 
            // Receive funds
            TransferHelper.safeTransferFrom(stakedToken, msg.sender, address(this), _newDeposit.body);
        }      
    }

    function addFundsToDeposit(uint256 _depositIndex, uint256 _addAmount) external {
        Deposit storage d = deposits[msg.sender][_depositIndex];
        _accrueInterests(d);
        d.body += _addAmount;
        // Receive funds
        TransferHelper.safeTransferFrom(stakedToken, msg.sender, address(this), _addAmount);
    }

    function claimInterests(uint256 _depositIndex) external returns (uint256 claimedAmount) {
        Deposit storage d = deposits[msg.sender][_depositIndex];
        _accrueInterests(d);
        // amountParams[0] - is always interest that accrued but not payed yet
        claimedAmount = d.amountParams[0];
        d.amountParams[0] = 0;
        if (claimedAmount > 0) {
            TransferHelper.safeTransfer(stakedToken, msg.sender, claimedAmount);    
        }
    }

    function withdraw(uint256 _depositIndex) external returns (uint256 withdrawAmount){
        Deposit storage d = deposits[msg.sender][_depositIndex];
        // accrue interests(with MINT!!!!) and pay all interest to body
        _accrueInterests(d);
        _payInterestToBody(d); 
        withdrawAmount = d.body;
        //d.body = 0;
        _removeDepositRecord(_depositIndex);
        TransferHelper.safeTransfer(stakedToken, msg.sender, withdrawAmount);
    }

    function withdrawEmergency(uint256 _depositIndex) external returns (uint256 withdrawAmount){
        Deposit storage d = deposits[msg.sender][_depositIndex];
        _payInterestToBody(d); 
        withdrawAmount = d.body;
        //d.body = 0;
        _removeDepositRecord(_depositIndex);
        TransferHelper.safeTransfer(stakedToken, msg.sender, withdrawAmount);
    }
    ///////////////////////////////////////////////////////////
    ///////    Admin Functions        /////////////////////////
    ///////////////////////////////////////////////////////////
    function modelRegister(DepositModel calldata _newModel) external onlyOwner {
        require(_newModel.modelAddress != address(0), "Cant be zero address");
        require(depositModels.length < type(uint8).max, "Too much models");
        depositModels.push(_newModel);
        emit DepositModelChanged(_newModel.modelAddress, _newModel.validAfter, _newModel.notValidAfter);
    }

    function editModelEndDate(uint256 _modelIndex, uint256 _notValidAfter) external onlyOwner {
        depositModels[_modelIndex].notValidAfter = _notValidAfter;
        emit DepositModelChanged(
            depositModels[_modelIndex].modelAddress, 
            depositModels[_modelIndex].validAfter, 
            _notValidAfter
        );  
    }
    ///////////////////////////////////////////////////////////
    function getUserDeposits(address _user) external view returns(Deposit[] memory) {
        return deposits[_user];
    }

    function getUserDeposits2(address _user) external view returns(Deposit[] memory) {
        Deposit[] memory uds = new Deposit[](deposits[_user].length);
        for (uint256 i = 0; i < uds.length; ++ i) {
            uds[i] = deposits[_user][i];     
        }
        return uds;
    }

    function getUserDepositsCount(address _user) external view returns(uint256) {
        return deposits[_user].length;
    }

    function getUserDepositByIndex(address _user, uint256 _index) 
        public 
        view 
        returns(Deposit memory) 
    {
        return deposits[_user][_index];
    }

    function getUserDepositByIndex2(address _user, uint256 _index) 
        public 
        view 
        returns(DepositInfo memory, uint256[] memory, address[] memory) 
    {
        Deposit memory d =  deposits[_user][_index];
        DepositInfo memory di;
        di.startDate = d.startDate;
        di.body = d.body;
        di.depositModelIndex = d.depositModelIndex;

        uint256[] memory amts = new uint256[](d.amountParams.length);
        address[] memory adrs = new address[](d.addressParams.length);
        for(uint256 i = 0; i < amts.length; ++ i){
            amts[i] = d.amountParams[i];
        }
        for(uint256 i = 0; i < adrs.length; ++ i){
            adrs[i] = d.addressParams[i];
        }
        return(di, amts, adrs);
    }


    function calcInterests(Deposit memory _deposit, uint256 _monthCount) 
        external 
        view
        returns(Deposit memory _newValues, uint256 increment)
    {
        (_newValues, increment) = IDepositModel(depositModels[_deposit.depositModelIndex].modelAddress)
            .calcInterests(_deposit, _monthCount);
    }

    function _accrueInterests(Deposit storage _deposit) 
        internal 
        returns(Deposit memory _newValues, uint256 increment)
    {
        (_newValues, increment) = IDepositModel(depositModels[_deposit.depositModelIndex].modelAddress)
            .accrueInterests(_deposit);
        _updateDepositInfo(_deposit, _newValues); 
        ISandbox1(rewardMintAddress).mintReward(address(this), increment);   
    }

    function _payInterestToBody(Deposit storage _deposit) internal returns(Deposit memory _newValues){
        _newValues = IDepositModel(depositModels[_deposit.depositModelIndex].modelAddress)
            .payInterestsToBody(_deposit);
        _updateDepositInfo(_deposit, _newValues);

    }

    function _insertNewDepositInfo(Deposit storage _deposit, Deposit memory _newValues) 
        internal 
        returns(Deposit memory)
    {
        _deposit.body = _newValues.body;
        _deposit.startDate = _newValues.startDate;
        _deposit.depositModelIndex = _newValues.depositModelIndex;
        for (uint256 i = 0; i < _newValues.amountParams.length; ++ i){
            _deposit.amountParams.push(_newValues.amountParams[i]);
        }

        for (uint256 i = 0; i < _newValues.addressParams.length; ++ i){
            _deposit.addressParams.push(_newValues.addressParams[i]);
        } 
        
    }

    function _updateDepositInfo(Deposit storage _deposit, Deposit memory _newValues) 
        internal 
        returns(Deposit memory)
    {
        _deposit.body = _newValues.body;
        //_deposit.startDate = _newValues.startDate;
        //_deposit.depositModelIndex = _newValues.depositModelIndex
        for (uint256 i = 0; i < _newValues.amountParams.length; ++ i){
            _deposit.amountParams[i] =_newValues.amountParams[i];
        }

        for (uint256 i = 0; i < _newValues.addressParams.length; ++ i){
            _deposit.addressParams[i] = _newValues.addressParams[i];
        } 
        
    }

    function _removeDepositRecord(uint256 _depositIndex) 
        internal 
    {
        Deposit[] storage userDeposits = deposits[msg.sender];
        if (_depositIndex != userDeposits.length -1) {
            userDeposits[_depositIndex] = userDeposits[userDeposits.length -1];
        }
        userDeposits.pop();
    }

}
// File: Ownable.sol



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

pragma solidity ^0.8.0;

import "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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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: Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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;
    }
}

// File: TransferHelper.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import "IERC20.sol";

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: IDepositModel.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;


struct Deposit {
    uint256 startDate;
    uint256 body;
    uint256[] amountParams;
    address[] addressParams;
    uint8 depositModelIndex;
}

struct DepositInfo {
    uint256 startDate;
    uint256 body;
    uint8 depositModelIndex;
}

interface IDepositModel  {

    event InterestsAccrued(
        uint256 indexed MonthNumber, 
        uint256 Rate, 
        uint256 BodyForCalc,  
        uint256 Interests
    );
    function checkOpen(address _user, Deposit memory _deposit) 
        external 
        view returns(bool ok, Deposit memory depositData);

    function accrueInterests(Deposit memory _deposit) 
        external 
        returns(Deposit memory, uint256 increment);
        
    function payInterestsToBody(Deposit memory _deposit) 
        external 
        returns(Deposit memory);

    function getRateForPeriodAndAmount(uint256 _amount, uint256 _currMonth) 
        external 
        view 
        returns(uint256);

    function calcInterests(Deposit memory _deposit, uint256 _monthCount) 
        external 
        view
        returns(Deposit memory, uint256 increment);
}
// File: ISandbox1.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;


interface ISandbox1  {
    function EXCHANGE_BASE_ASSET() external view returns (address);
    function TREASURY_TOPUP_PERCENT() external view returns (uint256);
    function mintReward(address _for, uint256 _amount) external;
    function ubdTokenAddress() external view returns (address);
}