contract StableV2 is Ownable, IStableV2 {
    using SafeMath for uint256;

    // Stable contains info related to each staker.
    struct Staker {
        uint256 amount;      // amount of tokens currently staked to the Stable
        uint256 correction;  // value needed for correct calculation staker's share
        uint256 banditsCorrection;
        uint256 distributed; // amount of distributed MILK tokens
    }

    // Default deflationarity parameters.
    uint256 private constant REDUCING_INTERVAL = 7 days; // 7 days is time between reductions
    uint256 private constant REDUCING_FACTOR = 10;       // production is reduced by 10%

    // MILK token contract.
    IMilker private _milker;

    // ERC20 token contract staking to the Stable.
    IERC20 private _token;

    // Stakers info by token holders.
    mapping(address => Staker) private _stakers;

    // Common variables configuring of the Stable.
    uint256 private _startTime;

    // Common variables describing current state of the Stable.
    uint256 private _banditsCorrection = 1e18;
    uint256 private _tokensPerShare;
    uint256 private _distributed;
    uint256 private _production;
    uint256 private _produced;
    uint256 private _lastUpdateTime;


    // Events.
    event Initialized(uint256 startTime, uint256 initialProduction);
    event Bandits(
        uint256 indexed percent,
        uint256 totalAmount,
        uint256 arrestedAmount,
        uint256 burntAmount
    );
    event Staked(address indexed staker, uint256 amount);
    event Claimed(address indexed staker, uint256 amount);


    modifier onlyMilker() {
        require(address(_milker) == _msgSender(), "StableV2: caller is not the Milker contract");
        _;
    }


    constructor(address milker, address token) public {
        require(address(milker) != address(0), "StableV2: Milker contract address cannot be empty");
        require(address(token) != address(0), "StableV2: ERC20 token contract address cannot be empty");
        _milker = IMilker(milker);
        _token = IERC20(token);
        transferOwnership(Ownable(milker).owner());
    }

    function initialize(uint256 startTime, uint256 initialProductionPerDay) external onlyOwner {
        require(produced() == 0, "StableV2: already started");
        _startTime = startTime;
        _production = 7 * initialProductionPerDay;
        _lastUpdateTime = _startTime;
        emit Initialized(_startTime, _production);
    }

    function stake(uint256 amount) external {
        address staker = msg.sender;
        require(!_milker.isWhitelisted(staker), "StableV2: whitelisted MILK holders cannot stake tokens");

        // Recalculate stable shares
        update();

        // Transfer pending tokens (if any) to the staker
        _shareMilk(staker);

        if (amount > 0) {
            // Transfer staking tokens to the StableV2 contract
            bool ok = _token.transferFrom(staker, address(this), amount);
            require(ok, "StableV2: unable to transfer stake");
            // Register staking tokens
            _stakers[staker].amount = _stakers[staker].amount.add(amount);
        }

        // Adjust correction (staker's reward debt)
        uint256 correction = _stakers[staker].amount.mul(_tokensPerShare).div(1e12);
        _stakers[staker].correction = correction.mul(1e18).div(_banditsCorrection);
        _stakers[staker].banditsCorrection = _banditsCorrection;

        // Emit event to the logs so can be effectively used later
        emit Staked(staker, amount);
    }

    function claim(uint256 amount) external {
        address staker = msg.sender;
        require(!_milker.isWhitelisted(staker), "StableV2: whitelisted MILK holders cannot claim tokens");

        // Recalculate stable shares
        update();

        // Transfer pending tokens (if any) to the staker
        _shareMilk(staker);

        if (amount > 0) {
            // Unregister claimed tokens
            _stakers[staker].amount = _stakers[staker].amount.sub(amount);
            // Transfer requested tokens from the StableV2 contract
            bool ok = _token.transfer(staker, amount);
            require(ok, "StableV2: unable to transfer stake");
        }

        // Adjust correction (staker's reward debt)
        uint256 correction = _stakers[staker].amount.mul(_tokensPerShare).div(1e12);
        _stakers[staker].correction = correction.mul(1e18).div(_banditsCorrection);
        _stakers[staker].banditsCorrection = _banditsCorrection;

        // Emit event to the logs so can be effectively used later
        emit Claimed(staker, amount);
    }

    ////////////////////////////////////////////////////////////////
    // Updating stable state
    ////////////////////////////////////////////////////////////////

    // Updates stable's accumulative data until most recent block.
    function update() public override {
        if (block.timestamp <= _lastUpdateTime) {
            return;
        }
        uint256 productionNew = production();
        uint256 producedNew = produced();
        if (producedNew <= _produced) {
            _lastUpdateTime = block.timestamp;
            return;
        }
        uint256 supply = tokenSupply();
        if (supply == 0) {
            (_production, _produced) = (productionNew, producedNew);
            _lastUpdateTime = block.timestamp;
            return;
        }
        // Produce MILK tokens to this contract
        uint256 producedTotal = producedNew.sub(_produced);
        uint256 producedToStable = _milker.produceMilk(producedTotal);
        // Update stable share price
        _tokensPerShare = _tokensPerShare.add(producedToStable.mul(1e12).div(supply));
        // Update stable state
        _production = productionNew;
        _produced = producedNew;
        _lastUpdateTime = block.timestamp;
    }

    ////////////////////////////////////////////////////////////////
    // Management functions callable only be Milker
    ////////////////////////////////////////////////////////////////

    function shareMilk(address taker) public override onlyMilker returns (uint256) {
        return _shareMilk(taker);
    }

    function bandits(uint256 percent) external override onlyMilker returns (
        uint256 banditsAmount,
        uint256 arrestedAmount,
        uint256 burntAmount
    ) {
        // Recalculate stable shares
        update();

        // Ensure pending amount and total tokens staked are not zero
        uint256 pendingAmount = milkSupply();
        if (pendingAmount == 0) {
            return (0, 0, 0);
        }

        // Calculate bandits amounts
        banditsAmount = pendingAmount.mul(percent).div(100);
        burntAmount = banditsAmount.div(10);
        arrestedAmount = banditsAmount.sub(burntAmount);

        // Transfer arrested MILK to the Sheriff's Vault
        _safeTransferMilk(address(_milker), arrestedAmount);

        // Decrease pending of each staker
        _banditsCorrection = _banditsCorrection.sub(_banditsCorrection.mul(percent).div(100));
        _tokensPerShare = _tokensPerShare.sub(_tokensPerShare.mul(percent).div(100));

        // Emit event to the logs so can be effectively used later
        emit Bandits(percent, banditsAmount, arrestedAmount, burntAmount);
    }

    ////////////////////////////////////////////////////////////////
    // Contract getters
    ////////////////////////////////////////////////////////////////

    function milker() public view override returns (address) {
        return address(_milker);
    }

    function token() public view override returns (address) {
        return address(_token);
    }

    function startTime() public view override returns (uint256) {
        return _startTime;
    }

    function stakerTokens(address staker) public view override returns (uint256) {
        return _stakers[staker].amount;
    }

    function stakerCorrection(address staker) public view override returns (uint256) {
        return _stakers[staker].correction;
    }

    function tokenSupply() public view override returns (uint256) {
        return _token.balanceOf(address(this));
    }

    function milkSupply() public view override returns (uint256) {
        return _milker.balanceOf(address(this));
    }

    ////////////////////////////////////////////////////////////////
    // MILK production related getters
    ////////////////////////////////////////////////////////////////

    function level() public view override returns (uint256) {
        if (_startTime == 0 || _startTime >= block.timestamp) {
            return 0;
        }
        return (block.timestamp - _startTime) / REDUCING_INTERVAL;
    }

    function levelProgress() public view override returns (uint256) {
        if (_startTime == 0 || _startTime >= block.timestamp) {
            return 0;
        }
        uint256 d = block.timestamp - (_startTime + level() * REDUCING_INTERVAL);
        return d * 10**18 / REDUCING_INTERVAL;
    }

    function production() public view override returns(uint256) {
        if (_startTime == 0 || _startTime >= block.timestamp) {
            return 0;
        }
        uint256 prod = _production;
        uint256 lvlA = (_lastUpdateTime - _startTime) / REDUCING_INTERVAL;
        uint256 lvlB = (block.timestamp - _startTime) / REDUCING_INTERVAL;
        for (; lvlA < lvlB; lvlA++) {
            prod -= prod / REDUCING_FACTOR;
        }
        return prod;
    }

    function produced() public view override returns(uint256) {
        if (_startTime == 0 || _startTime >= block.timestamp) {
            return 0;
        }
        uint256 lvlA = (_lastUpdateTime - _startTime) / REDUCING_INTERVAL;
        uint256 lvlB = (block.timestamp - _startTime) / REDUCING_INTERVAL;
        if (lvlA == lvlB) {
            return _produced + (block.timestamp - _lastUpdateTime) * _production / REDUCING_INTERVAL;
        }
        uint256 amount = 0;
        uint256 prod = _production;
        // Count end of first level
        amount += ((_startTime + (lvlA+1) * REDUCING_INTERVAL) - _lastUpdateTime) * prod / REDUCING_INTERVAL;
        prod -= prod / REDUCING_FACTOR;
        for (lvlA++; lvlA < lvlB; lvlA++) {
            // Count full level
            amount += prod;
            prod -= prod / REDUCING_FACTOR;
        }
        // Count start of current level
        amount += (block.timestamp - (_startTime + lvlB * REDUCING_INTERVAL)) * prod / REDUCING_INTERVAL;
        return _produced + amount;
    }

    function distributed() public view override returns(uint256) {
        return _distributed;
    }

    function pending() public view override returns(uint256) {
        uint256 p = produced();
        if (p <= _distributed) {
            return 0;
        }
        return p.sub(_distributed);
    }

    function pendingTo(address account) public view override returns (uint256) {
        uint256 added = produced().sub(_produced);
        uint256 supply = tokenSupply();
        uint256 tokensPerShare = _tokensPerShare;
        if (added > 0 && supply > 0) {
            tokensPerShare = tokensPerShare.add(added.sub(added.div(20)).mul(1e12).div(supply));
        }
        uint256 tokens = _stakers[account].amount.mul(tokensPerShare).div(1e12);
        uint256 correction = _stakers[account].correction.mul(_banditsCorrection).div(1e18);
        if (_banditsCorrection != _stakers[account].banditsCorrection) {
            correction = correction.mul(_stakers[account].banditsCorrection).div(_banditsCorrection);
        }
        if (tokens <= correction) {
            return 0;
        }
        return tokens.sub(correction);
    }

    ////////////////////////////////////////////////////////////////
    // Internal functions
    ////////////////////////////////////////////////////////////////

    function _shareMilk(address taker) private returns (uint256 tokens) {

        // Calculate pending tokens
        Staker storage s = _stakers[taker];
        uint256 pendingAmount = s.amount.mul(_tokensPerShare).div(1e12);
        uint256 correction = s.correction.mul(_banditsCorrection).div(1e18);
        if (_banditsCorrection != s.banditsCorrection) {
            correction = correction.mul(s.banditsCorrection).div(_banditsCorrection);
            s.banditsCorrection = _banditsCorrection;
        }
        if (pendingAmount > correction) {
            uint256 balance = _milker.balanceOf(address(this));
            pendingAmount = pendingAmount.sub(correction);
            tokens = pendingAmount > balance ? balance : pendingAmount;
            // Unregister sharing tokens
            s.correction = correction.add(tokens).mul(1e18).div(_banditsCorrection);
            s.banditsCorrection = _banditsCorrection;
            _distributed = _distributed.add(tokens);
            // Transfer MILK tokens from the StableV2 contract to the taker
            _safeTransferMilk(taker, tokens);
        }

        return tokens;
    }

    function _safeTransferMilk(address to, uint256 amount) private {
        uint256 balance = _milker.balanceOf(address(this));
        uint256 tokens = amount > balance ? balance : amount;
        if (tokens > 0) {
            bool ok = _milker.transfer(to, tokens);
            require(ok, "StableV2: unable to transfer MILK");
        }
    }

    ////////////////////////////////////////////////////////////////
    // [TESTS] Test functions to check internal state
    // TODO: Remove it since only for tests !!!
    ////////////////////////////////////////////////////////////////

    function testProduction() public view returns (uint256) {
        return _production;
    }

    function testProduced() public view returns (uint256) {
        return _produced;
    }

    function testTokensPerShare() public view returns (uint256) {
        return _tokensPerShare;
    }

    function testLastUpdateTime() public view returns (uint256) {
        return _lastUpdateTime;
    }
}
// solium-disable security/no-block-members
function _shareMilk(address taker) private returns (uint256 tokens) {

        // Calculate pending tokens
        Staker storage s = _stakers[taker];
        uint256 pendingAmount = s.amount.mul(_tokensPerShare).div(1e12);
        uint256 correction = s.correction.mul(_banditsCorrection).div(1e18);
        if (_banditsCorrection != s.banditsCorrection) {
            correction = correction.mul(s.banditsCorrection).div(_banditsCorrection);
            s.banditsCorrection = _banditsCorrection;
        }
        if (pendingAmount > correction) {
            uint256 balance = _milker.balanceOf(address(this));
            pendingAmount = pendingAmount.sub(correction);
            tokens = pendingAmount > balance ? balance : pendingAmount;
            // Unregister sharing tokens
            s.correction = correction.add(tokens).mul(1e18).div(_banditsCorrection);
            s.banditsCorrection = _banditsCorrection;
            _distributed = _distributed.add(tokens);
            // Transfer MILK tokens from the StableV2 contract to the taker
            _safeTransferMilk(taker, tokens);
        }

        return tokens;
    }
////////////////////////////////////////////////////////////////