contract Stakes is Owner, ReentrancyGuard {

    using SafeMath for uint256;

    // token    
    ERC20 public asset;

    // stakes history
    struct Record {
        uint256 from;
        uint256 amount;
        uint256 gain;
        uint256 penalization;
        uint256 to;
        bool ended;
    }

    // contract parameters
    uint8 public interest_rate;
    uint256 public maturity;
    uint8 public penalization;
    uint256 public lower_amount;

    mapping(address => Record[]) public ledger;

    event StakeStart(address indexed user, uint256 value, uint256 index);
    event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index);
    
    constructor(ERC20 _erc20, address _owner, uint8 _rate, uint256 _maturity, uint8 _penalization, uint256 _lower) Owner(_owner) {
        require(_penalization<=100, "Penalty has to be an integer between 0 and 100");
        asset = _erc20;
        interest_rate = _rate;
        maturity = _maturity;
        penalization = _penalization;
        lower_amount = _lower;
    }
    
    function start(uint256 _value) external {
        require(_value >= lower_amount, "Invalid value");
        asset.transferFrom(msg.sender, address(this), _value);
        ledger[msg.sender].push(Record(block.timestamp, _value, 0, 0, 0, false));
        emit StakeStart(msg.sender, _value, ledger[msg.sender].length-1);
    }

    function end(uint256 i) external nonReentrant {

        require(i < ledger[msg.sender].length, "Invalid index");
        require(ledger[msg.sender][i].ended==false, "Invalid stake");
        
        // penalization
        if(block.timestamp.sub(ledger[msg.sender][i].from) < maturity) {
            uint256 _penalization = ledger[msg.sender][i].amount.mul(penalization).div(100);
            asset.transfer(msg.sender, ledger[msg.sender][i].amount.sub(_penalization));
            asset.transfer(getOwner(), _penalization);
            ledger[msg.sender][i].penalization = _penalization;
            ledger[msg.sender][i].to = block.timestamp;
            ledger[msg.sender][i].ended = true;
            emit StakeEnd(msg.sender, ledger[msg.sender][i].amount, _penalization, 0, i);
        // interest gained
        } else {
            uint256 _interest = get_gains(msg.sender, i);
            // check that the owner can pay interest before trying to pay
            if (asset.allowance(getOwner(), address(this)) >= _interest && asset.balanceOf(getOwner()) >= _interest) {
                asset.transferFrom(getOwner(), msg.sender, _interest);
            } else {
                _interest = 0;
            }
            asset.transfer(msg.sender, ledger[msg.sender][i].amount);
            ledger[msg.sender][i].gain = _interest;
            ledger[msg.sender][i].to = block.timestamp;
            ledger[msg.sender][i].ended = true;
            emit StakeEnd(msg.sender, ledger[msg.sender][i].amount, 0, _interest, i);
        }
    }

    function set(uint256 _lower, uint256 _maturity, uint8 _rate, uint8 _penalization) public isOwner {
        require(_penalization<=100, "Invalid value");
        lower_amount = _lower;
        maturity = _maturity;
        interest_rate = _rate;
        penalization = _penalization;
    }
    
    // calculate interest to the current date time
    function get_gains(address _address, uint256 _rec_number) public view returns (uint256) {
        uint256 _record_seconds = block.timestamp.sub(ledger[_address][_rec_number].from);
        uint256 _year_seconds = 365*24*60*60;
        return _record_seconds.mul(
            ledger[_address][_rec_number].amount.mul(interest_rate).div(100)
        ).div(_year_seconds);
    }

    function ledger_length(address _address) public view returns (uint256) {
        return ledger[_address].length;
    }

}
/**
 * 
 * Stakes is an interest gain contract for ERC-20 tokens
 * 
 * assets is the ERC20 token
 * interest_rate: percentage rate
 * maturity is the time in seconds after which is safe to end the stake
 * penalization for ending a stake before maturity time
 * lower_amount is the minimum amount for creating a stake
 * 
 */
function get_gains(address _address, uint256 _rec_number) public view returns (uint256) {
    uint256 _record_seconds = block.timestamp.sub(ledger[_address][_rec_number].from);
    uint256 _year_seconds = 365*24*60*60;
    return _record_seconds.mul(
        ledger[_address][_rec_number].amount.mul(interest_rate).div(100)
    ).div(_year_seconds);
}

// calculate interest to the current date time