contract Milk is Ownable, IMilker {
    using SafeMath for uint256;

    // Stable related info needed for proper shares calculation.
    struct StableInfo {
        IStableV2 stable;
    }

    // Token details.
    string public constant name = "Cowboy.Finance";
    string public constant symbol = "MILK";
    uint256 public constant decimals = 18;

    // Token supply limitations.
    uint256 private constant MAX_UINT256 = ~uint256(0);
    uint256 private constant MAX_SUPPLY = 7_000_000 * 10**decimals;
    uint256 private constant TOTAL_UNITS = MAX_UINT256 - (MAX_UINT256 % MAX_SUPPLY);

    // Period length is a time of events recharging.
    uint256 private constant PERIOD_LENGTH = 6 hours;

    // Hardcoded address to collect 5% developers team share.
    address private constant _devs = 0xFFCF83437a1Eb718933f39ebE75aD96335BC1BE4;

    // Address of controller contract from which base refase functions can be called.
    address private _controller;

    // Token holders balances "in hand", balances in vaults, and spending allowances.
    mapping(address => uint256) private _balances; // in units
    mapping(address => uint256) private _vaults;   // in units
    mapping(address => mapping (address => uint256)) private _allowances; // in tokens

    // Whitelisted addresses.
    mapping(address => bool) private _whitelist;

    // Registered stables.
    StableInfo[] private _stables;
    mapping(address => uint256) _stablesLookup;

    // Time of start token life.
    uint256 private _startTime;

    // Token supplies.
    uint256 private _supplyInBalances;      // in units
    uint256 private _supplyInSheriffsVault; // in units
    uint256 private _supplyInSheriffsPot;   // in tokens
    uint256 private _totalSupply;           // in tokens

    // Values needed to convert between units and tokens (divided to several parts).
    uint256 private _unitsPerTokenInBalances = TOTAL_UNITS.div(MAX_SUPPLY);
    uint256 private _unitsPerTokenInSheriffsVault = TOTAL_UNITS.div(MAX_SUPPLY);

    // Contract configuration events.
    event ControllerSetUp(address indexed controller);
    event StableCreated(address stable, address milker, address token, uint256 id);

    // ERC20 token related events.
    event Mint(address indexed recipient, uint256 amount);
    event Burn(address indexed stable, uint256 amount);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    // Tokenomics mechanics events.
    event Bandits(
        uint256 indexed percent,
        uint256 totalAmount,
        uint256 arrestedAmount,
        uint256 burntAmount
    );
    event SheriffsVaultCommission(uint256 amount);
    event SheriffsPotDistribution(uint256 amount);

    // Sheriff's Vault staking/unstaking events.
    event SheriffsVaultDeposit(address indexed account, uint256 amount);
    event SheriffsVaultWithdraw(address indexed account, uint256 amount);


    modifier validRecipient(address account) {
        require(account != address(0x0), "Milk: unable to send tokens to zero address");
        _;
    }

    modifier onlyController() {
        require(_controller == _msgSender(), "Milk: caller is not the controller");
        _;
    }

    modifier onlyStable() {
        require(_stablesLookup[_msgSender()] > 0, "Milk: caller is not the StableV2");
        _;
    }


    constructor() public {
        _whitelist[_devs] = true;
        _startTime = block.timestamp;
    }

    ////////////////////////////////////////////////////////////////
    // [Administration] Contract admin managing
    ////////////////////////////////////////////////////////////////

    function setController(address controller) external onlyOwner {
        _controller = controller;
        emit ControllerSetUp(controller);
    }

    function createStable(address token) external onlyOwner returns (address stable) {

        // Deploy StableV2 contract
        bytes32 salt = keccak256(abi.encodePacked(address(this), token));
        stable = address(new StableV2{salt: salt}(address(this), token));
        require(stable != address(0), "Milk: unable to create deploy StableV2 contract");

        // Register created Stable
        _stables.push(StableInfo({stable: IStableV2(stable)}));
        _stablesLookup[stable] = _stables.length;
        _whitelist[stable] = true;

        // Also set token as whitelist
        if (!_whitelist[token]) {
            uint256 amount = _balances[token].div(_unitsPerTokenInBalances);
            _supplyInBalances = _supplyInBalances.sub(_balances[token]);
            _balances[token] = amount;
            _whitelist[token] = true;
        }

        emit StableCreated(stable, address(this), token, _stables.length - 1);
    }

    ////////////////////////////////////////////////////////////////
    // [Event] Bandits are coming!
    ////////////////////////////////////////////////////////////////

    function bandits(uint256 percent) external override onlyController returns (
        uint256 banditsAmount,
        uint256 arrestedAmount,
        uint256 burntAmount
    ) {
        require(percent > 0 && percent < 100, "Milker: invalid bandits percent");
        uint256 supply = _supplyInBalances.div(_unitsPerTokenInBalances);

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

        // Burn necessary amount of MILK tokens in each stable
        uint256 banditsPending;
        uint256 arrestedPending;
        uint256 burntPending;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            (uint256 b, uint256 a, uint256 x) = _stables[i].stable.bandits(percent);
            // Calculate bandits pending amounts
            banditsPending = banditsPending.add(b);
            arrestedPending = arrestedPending.add(a);
            burntPending = burntPending.add(x);
            // Burn MILK from the Stable contract
            _burn(address(_stables[i].stable), x);
        }

        // Update supplies
        uint256 supplyNew = supply.sub(banditsAmount);
        if (supply > 0 && supplyNew > 0) {
            _unitsPerTokenInBalances = supply.mul(_unitsPerTokenInBalances).div(supplyNew);
            _supplyInBalances = supplyNew.mul(_unitsPerTokenInBalances);
            _supplyInSheriffsPot = _supplyInSheriffsPot.add(arrestedAmount).add(arrestedPending);
            _totalSupply = _totalSupply.sub(burntAmount);
        }

        // Calculate final bandits amounts
        banditsAmount = banditsAmount.add(banditsPending);
        arrestedAmount = arrestedAmount.add(arrestedPending);
        burntAmount = burntAmount.add(burntPending);

        emit Bandits(percent, banditsAmount, arrestedAmount, burntAmount);
    }

    ////////////////////////////////////////////////////////////////
    // [Event] Sheriff's Vault commission
    ////////////////////////////////////////////////////////////////

    function sheriffsVaultCommission() external override onlyController returns (uint256) {

        // Calculate comission in both units and tokens
        uint256 vunits = _supplyInSheriffsVault.div(100);
        uint256 tokens = vunits.div(_unitsPerTokenInSheriffsVault);

        // Update supplies
        uint256 supply = _supplyInSheriffsVault.div(_unitsPerTokenInSheriffsVault);
        uint256 supplyNew = supply.sub(supply.div(100));
        if (supply > 0 && supplyNew > 0) {
            _unitsPerTokenInSheriffsVault = supply.mul(_unitsPerTokenInSheriffsVault).div(supplyNew);
            _supplyInSheriffsVault = supplyNew.mul(_unitsPerTokenInSheriffsVault);
            _supplyInSheriffsPot = _supplyInSheriffsPot.add(tokens);
        } else {
            tokens = 0;
        }

        emit SheriffsVaultCommission(tokens);
        return tokens;
    }

    ////////////////////////////////////////////////////////////////
    // [Event] Sheriff's Pot distribution
    ////////////////////////////////////////////////////////////////

    function sheriffsPotDistribution() external override onlyController returns (uint256 amount) {
        uint256 tokens = _supplyInSheriffsPot;
        if (tokens == 0 || _supplyInBalances == 0) {
            return 0;
        }

        // Update supplies
        uint256 supply = _supplyInBalances.div(_unitsPerTokenInBalances);
        uint256 supplyNew = supply.add(tokens);
        _unitsPerTokenInBalances = supply.mul(_unitsPerTokenInBalances).div(supplyNew);
        _supplyInBalances = supplyNew.mul(_unitsPerTokenInBalances);
        _supplyInSheriffsPot = 0;

        emit SheriffsPotDistribution(tokens);
        return tokens;
    }

    ////////////////////////////////////////////////////////////////
    // Sheriff's Vault
    ////////////////////////////////////////////////////////////////

    function putToSheriffsVault(uint256 amount) external {
        address account = msg.sender;
        require(!_whitelist[account], "Milk: whitelisted holders cannot use Sheriff's Vault");

        // Take pending MILK
        takeMilk(account);

        // Calculate amount in units
        uint256 unitsInBalances = amount.mul(_unitsPerTokenInBalances);
        uint256 unitsInSheriffsVault = amount.mul(_unitsPerTokenInSheriffsVault);

        // Update balances and vaults records
        _balances[account] = _balances[account].sub(unitsInBalances);
        _vaults[account] = _vaults[account].add(unitsInSheriffsVault);

        // Update supplies
        _supplyInBalances = _supplyInBalances.sub(unitsInBalances);
        _supplyInSheriffsVault = _supplyInSheriffsVault.add(unitsInSheriffsVault);

        emit SheriffsVaultDeposit(account, amount);
    }

    function takeFromSheriffsVault(uint256 amount) external {
        address account = msg.sender;
        require(!_whitelist[account], "Milk: whitelisted holders cannot use Sheriff's Vault");

        // Take pending MILK
        takeMilk(account);

        // Calculate amount in units
        uint256 unitsInBalances = amount.mul(_unitsPerTokenInBalances);
        uint256 unitsInSheriffsVault = amount.mul(_unitsPerTokenInSheriffsVault);

        // Update balances and vaults records
        _balances[account] = _balances[account].add(unitsInBalances);
        _vaults[account] = _vaults[account].sub(unitsInSheriffsVault);

        // Update supplies
        _supplyInBalances = _supplyInBalances.add(unitsInBalances);
        _supplyInSheriffsVault = _supplyInSheriffsVault.sub(unitsInSheriffsVault);

        emit SheriffsVaultWithdraw(account, amount);
    }

    ////////////////////////////////////////////////////////////////
    // [Token] Minting/burning token
    ////////////////////////////////////////////////////////////////

    function mint(address recipient, uint256 amount) external validRecipient(recipient) onlyOwner returns (bool) {
        if (isWhitelisted(recipient)) {
            _balances[recipient] = _balances[recipient].add(amount);
        } else {
            uint256 units = amount.mul(_unitsPerTokenInBalances);
            _balances[recipient] = _balances[recipient].add(units);
            _supplyInBalances = _supplyInBalances.add(units);
        }
        _totalSupply = _totalSupply.add(amount);
        emit Mint(recipient, amount);
        emit Transfer(address(0), recipient, amount);
        return true;
    }

    function takeMilk(address account) public override returns (uint256) {
        uint256 tokens;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            _stables[i].stable.update();
            uint256 transferred = _stables[i].stable.shareMilk(account);
            tokens = tokens.add(transferred);
        }
        return tokens;
    }

    ////////////////////////////////////////////////////////////////
    // [Token] Issuing/transferring earned tokens
    ////////////////////////////////////////////////////////////////

    function produceMilk(uint256 amount) public override onlyStable returns (uint256) {
        // Substruct 5% from each amount to transfer to the developers team
        uint256 devsFee = amount.div(20);      //  5%
        uint256 stabled = amount.sub(devsFee); // 95%
        // Produce (mint) MILK tokens
        _balances[msg.sender] = _balances[msg.sender].add(stabled);
        _balances[_devs] = _balances[_devs].add(devsFee);
        _totalSupply = _totalSupply.add(amount);
        // emit Mint(msg.sender, amount);
        emit Transfer(address(0), msg.sender, stabled);
        emit Transfer(address(0), _devs, devsFee);
        return stabled;
    }

    ////////////////////////////////////////////////////////////////
    // [Token] Transferring token
    ////////////////////////////////////////////////////////////////

    function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) {
        (address from, bool fromWT, bool toWT) = (msg.sender, isWhitelisted(msg.sender), isWhitelisted(to));
        uint256 unitsFrom = fromWT ? value : value.mul(_unitsPerTokenInBalances);
        uint256 unitsTo = toWT ? value : value.mul(_unitsPerTokenInBalances);
        if (!fromWT && _balances[from] < unitsFrom) {
            takeMilk(from);
        }
        if (fromWT && toWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
        } else if (fromWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
            _supplyInBalances = _supplyInBalances.add(unitsTo);
        } else if (toWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
            _supplyInBalances = _supplyInBalances.sub(unitsFrom);
        } else {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
        }
        emit Transfer(from, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint256 value) public override validRecipient(to) returns (bool) {
        (bool fromWT, bool toWT) = (isWhitelisted(msg.sender), isWhitelisted(to));
        uint256 unitsFrom = fromWT ? value : value.mul(_unitsPerTokenInBalances);
        uint256 unitsTo = toWT ? value : value.mul(_unitsPerTokenInBalances);
        _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
        if (!fromWT && _balances[from] < unitsFrom) {
            takeMilk(from);
        }
        if (fromWT && toWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
        } else if (fromWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
            _supplyInBalances = _supplyInBalances.add(unitsTo);
        } else if (toWT) {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
            _supplyInBalances = _supplyInBalances.sub(unitsFrom);
        } else {
            _balances[from] = _balances[from].sub(unitsFrom);
            _balances[to] = _balances[to].add(unitsTo);
        }
        emit Transfer(from, to, value);
        return true;
    }

    function approve(address spender, uint256 value) public override returns (bool) {
        _allowances[msg.sender][spender] = value;
        emit Approval(msg.sender, spender, value);
        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
        _allowances[msg.sender][spender] = _allowances[msg.sender][spender].add(addedValue);
        emit Approval(msg.sender, spender, _allowances[msg.sender][spender]);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
        uint256 oldValue = _allowances[msg.sender][spender];
        if (subtractedValue >= oldValue) {
            _allowances[msg.sender][spender] = 0;
        } else {
            _allowances[msg.sender][spender] = oldValue.sub(subtractedValue);
        }
        emit Approval(msg.sender, spender, _allowances[msg.sender][spender]);
        return true;
    }

    ////////////////////////////////////////////////////////////////
    // Common getters
    ////////////////////////////////////////////////////////////////

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

    function isWhitelisted(address account) public view override returns (bool) {
        return _whitelist[account];
    }

    function stable(uint256 index) public view returns (address) {
        return index < _stables.length ? address(_stables[index].stable) : address(0);
    }

    function stables() public view returns (address[] memory) {
        address[] memory addresses = new address[](_stables.length);
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            addresses[i] = address(_stables[i].stable);
        }
        return addresses;
    }

    function stableCount() public view returns (uint256) {
        return _stables.length;
    }

    function balanceOf(address account) public view override returns (uint256) {
        // For whitelisted addresses don't calculate pending tokens
        if (isWhitelisted(account)) {
            return _balances[account];
        }
        // Summarize pending MILK from all stables
        uint256 pendingAmount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            pendingAmount = pendingAmount.add(_stables[i].stable.pendingTo(account));
        }
        // Final balance is actually summ of acked and pending MILK
        return _balances[account].div(_unitsPerTokenInBalances).add(pendingAmount);
    }

    function vaultOf(address account) public view override returns (uint256) {
        return _vaults[account].div(_unitsPerTokenInSheriffsVault);
    }

    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function holdersSupply() public view returns (uint256) {
        return _supplyInBalances.div(_unitsPerTokenInBalances);
    }

    function sheriffsPotSupply() public view returns (uint256) {
        return _supplyInSheriffsPot;
    }

    function sheriffsVaultSupply() public view returns (uint256) {
        return _supplyInSheriffsVault.div(_unitsPerTokenInSheriffsVault);
    }

    ////////////////////////////////////////////////////////////////
    // Token lifetime related getters
    ////////////////////////////////////////////////////////////////

    function period() public view override returns (uint256) {
        return block.timestamp.sub(_startTime).div(PERIOD_LENGTH);
    }

    function periodProgress() public view override returns (uint256) {
        uint256 durationFromPeriodStart = block.timestamp
            .sub(_startTime.add(period().mul(PERIOD_LENGTH)));
        return durationFromPeriodStart.mul(10**18).div(PERIOD_LENGTH);
    }

    function periodLength() public view override returns (uint256) {
        return PERIOD_LENGTH;
    }

    ////////////////////////////////////////////////////////////////
    // Token production related getters
    ////////////////////////////////////////////////////////////////

    function production() public view override returns(uint256) {
        uint256 amount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            amount = amount.add(_stables[i].stable.production());
        }
        return amount;
    }

    function producedTotal() public view override returns(uint256) {
        uint256 amount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            amount = amount.add(_stables[i].stable.produced());
        }
        return amount;
    }

    function distributedTotal() public view override returns(uint256) {
        uint256 amount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            amount = amount.add(_stables[i].stable.distributed());
        }
        return amount;
    }

    function pendingTotal() public view override returns(uint256) {
        uint256 amount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            amount = amount.add(_stables[i].stable.pending());
        }
        return amount;
    }

    function pendingTo(address account) public view override returns(uint256) {
        uint256 amount;
        for ((uint256 i, uint256 c) = (0, _stables.length); i < c; i++) {
            amount = amount.add(_stables[i].stable.pendingTo(account));
        }
        return amount;
    }

    function unitsPerToken() public view returns (uint256) {
        return _unitsPerTokenInBalances;
    }

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

    function _burn(address burner, uint256 amount) private {
        _balances[burner] = _balances[burner].sub(amount);
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(burner, address(0), amount);
        // emit Burn(burner, amount);
    }
}
function sheriffsVaultCommission() external override onlyController returns (uint256) {

        // Calculate comission in both units and tokens
        uint256 vunits = _supplyInSheriffsVault.div(100);
        uint256 tokens = vunits.div(_unitsPerTokenInSheriffsVault);

        // Update supplies
        uint256 supply = _supplyInSheriffsVault.div(_unitsPerTokenInSheriffsVault);
        uint256 supplyNew = supply.sub(supply.div(100));
        if (supply > 0 && supplyNew > 0) {
            _unitsPerTokenInSheriffsVault = supply.mul(_unitsPerTokenInSheriffsVault).div(supplyNew);
            _supplyInSheriffsVault = supplyNew.mul(_unitsPerTokenInSheriffsVault);
            _supplyInSheriffsPot = _supplyInSheriffsPot.add(tokens);
        } else {
            tokens = 0;
        }

        emit SheriffsVaultCommission(tokens);
        return tokens;
    }
////////////////////////////////////////////////////////////////