contract StabilizeStrategyStablecoinArbV2 is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    using Address for address;
    
    address public treasuryAddress; // Address of the treasury
    address public stakingAddress; // Address to the STBZ staking pool
    address public zsTokenAddress; // The address of the controlling zs-Token
    
    uint256 constant divisionFactor = 100000;
    uint256 public secondsBeforeTrade = 86400; // Default 24 hours wait before trade triggered automatically
    uint256 public lastTradeTime = 0;
    uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
    uint256 public percentTradeTrigger = 10000; // 10% change in value will trigger a trade
    uint256 public percentSell = 50000; // 50% of the tokens are sold to the cheapest token
    uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
    uint256 public percentExecutor = 20000; // 20000 = 20% of WETH goes to executor
    uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
    uint256 public minReserve = 1000; // The minimum amount of stablecoin requested of the lowest priced coin
    uint256 public minTradeSplit = 1000; // If the balance of a stablecoin is less than or equal to this, it trades the entire balance
    uint256 constant minGain = 1e16; // Minimum amount of stablecoin gain (about 0.01 USD) before buying WETH and splitting it
    
    // Token information
    // This strategy accepts multiple stablecoins
    // DAI, USDC, USDT, sUSD
    struct TokenInfo {
        IERC20 token; // Reference of token
        uint256 decimals; // Decimals of token
        uint256 price; // Last price of token in USD
        int128 curveID; // ID in the curve Pool
    }
    
    TokenInfo[] private tokenList; // An array of tokens accepted as deposits
    StabilizePriceOracle private oracleContract; // A reference to the price oracle contract
    
    // Strategy specific variables
    address constant curveAddress = address(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD); // Curve pool for 4 token DAI, USDC, USDT, sUSD
    address constant uniswapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap

    constructor(
        address _treasury,
        address _staking,
        address _zsToken,
        StabilizePriceOracle _oracle
    ) public {
        treasuryAddress = _treasury;
        stakingAddress = _staking;
        zsTokenAddress = _zsToken;
        oracleContract = _oracle;
        setupWithdrawTokens();
    }

    // Initialization functions
    
    function setupWithdrawTokens() internal {
        // Start with DAI
        IERC20 _token = IERC20(address(0x6B175474E89094C44Da98b954EedeAC495271d0F));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals(),
                price: 1e18,
                curveID: 0
            })
        );   
        
        // USDC
        _token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals(),
                price: 1e18,
                curveID: 1
            })
        );
        
        // USDT
        _token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals(),
                price: 1e18,
                curveID: 2
            })
        );
        
        // sUSD
        _token = IERC20(address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals(),
                price: 1e18,
                curveID: 3
            })
        );
    }
    
    // Modifier
    modifier onlyZSToken() {
        require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
        _;
    }
    
    // Read functions
    
    function rewardTokensCount() external view returns (uint256) {
        return tokenList.length;
    }
    
    function rewardTokenAddress(uint256 _pos) external view returns (address) {
        require(_pos < tokenList.length,"No token at that position");
        return address(tokenList[_pos].token);
    }
    
    function balance() public view returns (uint256) {
        return getNormalizedTotalBalance(address(this));
    }
    
    function getNormalizedTotalBalance(address _address) public view returns (uint256) {
        uint256 _balance = 0;
        for(uint256 i = 0; i < tokenList.length; i++){
            uint256 _bal = tokenList[i].token.balanceOf(_address);
            _bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
            _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
        }
        return _balance;
    }
    
    function withdrawTokenReserves() public view returns (address, uint256) {
        // This function will return the address and amount of the token with the lowest price
        uint256 length = tokenList.length;
        uint256 targetID = 0;
        uint256 targetPrice = 0;
        for(uint256 i = 0; i < length; i++){
            if(tokenList[i].token.balanceOf(address(this)) > 0){
                uint256 _price = tokenList[i].price;
                if(targetPrice == 0 || _price <= targetPrice){
                    targetPrice = _price;
                    targetID = i;
                }
            }
        }
        if(targetPrice > 0){
            return (address(tokenList[targetID].token), tokenList[targetID].token.balanceOf(address(this)));
        }else{
            return (address(0), 0); // No balance
        }
    }
    
    // Write functions
    
    function enter() external onlyZSToken {
        deposit(false);
    }
    
    function exit() external onlyZSToken {
        // The ZS token vault is removing all tokens from this strategy
        withdraw(_msgSender(),1,1, false);
    }
    
    function deposit(bool nonContract) public onlyZSToken {
        // Only the ZS token can call the function
        
        // No trading is performed on deposit
        if(nonContract == true){}
        lastActionBalance = balance();
    }
    
    function getCheapestCurveToken() internal view returns (uint256) {
        // This will give us the ID of the cheapest token in the pool
        // We will estimate the return for trading 1000 DAI
        // The higher the return, the lower the price of the other token
        uint256 targetID = 0; // Our target ID is DAI first
        CurvePool pool = CurvePool(curveAddress);
        uint256 daiAmount = uint256(1000).mul(10**tokenList[0].decimals);
        uint256 highAmount = daiAmount;
        for(uint256 i = 1; i < tokenList.length; i++){
            uint256 estimate = pool.get_dy_underlying(tokenList[0].curveID, tokenList[i].curveID, daiAmount);
            // Normalize the estimate into DAI decimals
            estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
            if(estimate > highAmount){
                // This token is worth less than the DAI
                highAmount = estimate;
                targetID = i;
            }
        }
        return targetID;
    }
    
    function checkAndSwapTokens(bool _restrictSwaps, address _executor) internal {
        lastTradeTime = now;
        CurvePool pool = CurvePool(curveAddress);
        
        // Now find our target token to sell into
        uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
        uint256 length = tokenList.length;
        
        if(_restrictSwaps == true){
            // Check if target ID has more than minimum reserve
            uint256 _minReserveTarget = minReserve.mul(10**tokenList[targetID].decimals);
            if(tokenList[targetID].token.balanceOf(address(this)) < _minReserveTarget){
                // If less, we want to fill the reserve
                _restrictSwaps = false;
            }
        }
        
        // Now sell all the other tokens into this token
        uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
        bool _expectIncrease = false;
        for(uint256 i = 0; i < length; i++){
            if(i != targetID){
                uint256 localTarget = targetID;
                if(_restrictSwaps == true){
                    // When restrict swaps is true, DAI will only sell to sUSD and sUSD will only sell to DAI as these pairs swap prices frequently
                    if(i == 0){ // DAI
                        localTarget = 3; // sUSD
                    }else if(i == 3){ // sUSD
                        localTarget = 0; // DAI
                    }                  
                }
                uint256 sellBalance = 0;
                uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
                if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
                    // We have a small amount of tokens to sell, so sell all of it
                    sellBalance = tokenList[i].token.balanceOf(address(this));
                }else{
                    sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(divisionFactor);
                }
                uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
                if(sellBalance > 0){
                    uint256 estimate = pool.get_dy_underlying(tokenList[i].curveID, tokenList[localTarget].curveID, sellBalance);
                    if(estimate > minReceiveBalance){
                        _expectIncrease = true;
                        // We are getting a greater number of tokens, complete the exchange
                        tokenList[i].token.safeApprove(address(pool), sellBalance);
                        pool.exchange_underlying(tokenList[i].curveID, tokenList[localTarget].curveID, sellBalance, minReceiveBalance);
                    }                        
                }
            }
        }
        uint256 _newBalance = balance();
        if(_expectIncrease == true){
            // There may be rare scenarios where we don't gain any by calling this function
            require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
        }
        uint256 gain = _newBalance.sub(_totalBalance);
        if(gain >= minGain){
            // Minimum gain required to buy WETH is about $0.01
            // Buy WETH from Uniswap with stablecoin
            uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18);
            uint256 holdBalance = sellBalance.mul(percentDepositor).div(divisionFactor);
            sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
            if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
                UniswapRouter router = UniswapRouter(uniswapRouterAddress);
                IERC20 weth = IERC20(router.WETH());
                // Sell some of our gained stablecoins for WETH
                swapUniswap(address(tokenList[targetID].token), address(weth), sellBalance);
                uint256 _wethBalance = weth.balanceOf(address(this));
                if(_wethBalance > 0){
                    // Split the amount sent to the treasury, stakers and executor if one exists
                    if(_executor != address(0)){
                        // First send the executor a percentage of the profit
                        uint256 executorAmount = _wethBalance.mul(percentExecutor).div(divisionFactor);
                        if(executorAmount > 0){
                            weth.safeTransfer(_executor, executorAmount);
                            _wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract                          
                        }
                    }
                    uint256 stakersAmount = _wethBalance.mul(percentStakers).div(divisionFactor);
                    uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
                    if(treasuryAmount > 0){
                        weth.safeTransfer(treasuryAddress, treasuryAmount);
                    }
                    if(stakersAmount > 0){
                        if(stakingAddress != address(0)){
                            weth.safeTransfer(stakingAddress, stakersAmount);
                            StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);                                
                        }else{
                            // No staking pool selected, just send to the treasury
                            weth.safeTransfer(treasuryAddress, stakersAmount);
                        }
                    }
                }
            }
        }
    }
    
    function expectedProfit(bool _restrictSwaps) external view returns (uint256) {
        // This view will return the expected profit in wei units that a trading activity will have on the pool
        CurvePool pool = CurvePool(curveAddress);
        
        // Now find our target token to sell into
        uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
        uint256 length = tokenList.length;
        
        if(_restrictSwaps == true){
            // Check if target ID has more than minimum reserve
            uint256 _minReserveTarget = minReserve.mul(10**tokenList[targetID].decimals);
            if(tokenList[targetID].token.balanceOf(address(this)) < _minReserveTarget){
                // If less, we want to fill the reserve
                _restrictSwaps = false;
            }
        }
        
        // Now sell all the other tokens into this token
        uint256 _normalizedGain = 0;
        for(uint256 i = 0; i < length; i++){
            if(i != targetID){
                uint256 localTarget = targetID;
                if(_restrictSwaps == true){
                    // When restrict swaps is true, DAI will only sell to sUSD and sUSD will only sell to DAI as these pairs swap prices frequently
                    if(i == 0){ // DAI
                        localTarget = 3; // sUSD
                    }else if(i == 3){ // sUSD
                        localTarget = 0; // DAI
                    }                  
                }
                uint256 sellBalance = 0;
                uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
                if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
                    // We have a small amount of tokens to sell, so sell all of it
                    sellBalance = tokenList[i].token.balanceOf(address(this));
                }else{
                    sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(divisionFactor);
                }
                uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
                if(sellBalance > 0){
                    uint256 estimate = pool.get_dy_underlying(tokenList[i].curveID, tokenList[localTarget].curveID, sellBalance);
                    if(estimate > minReceiveBalance){
                        uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[localTarget].decimals); // Normalized gain
                        _normalizedGain = _normalizedGain.add(_gain);
                    }                        
                }
            }
        }
        return _normalizedGain;
    }
    
    function swapUniswap(address _from, address _to, uint256 _sellAmount) internal {
        require(_to != address(0));

        address[] memory path;
        UniswapRouter router = UniswapRouter(uniswapRouterAddress);
        address weth = router.WETH();

        if (_from == weth || _to == weth) {
            path = new address[](2);
            path[0] = _from;
            path[1] = _to;
        } else {
            path = new address[](3);
            path[0] = _from;
            path[1] = weth;
            path[2] = _to;
        }

        IERC20(_from).safeApprove(address(router), 0); // Some tokens require this to be set to 0 first
        IERC20(_from).safeApprove(address(router), _sellAmount);
        router.swapExactTokensForTokens(_sellAmount, 1, path, address(this), now.add(60));
    }
    
    function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
        require(balance() > 0, "There are no tokens in this strategy");
        if(nonContract == true){
            if(now.sub(lastTradeTime) > secondsBeforeTrade || _share > _total.mul(percentTradeTrigger).div(divisionFactor)){
                checkAndSwapTokens(true, _depositor);
            }
        }
        
        uint256 withdrawAmount = 0;
        uint256 _balance = balance();
        if(_share < _total){
            uint256 _myBalance = _balance.mul(_share).div(_total);
            withdrawPerPrice(_depositor, _myBalance, false); // This will withdraw based on token price
            withdrawAmount = _myBalance;
        }else{
            // We are all shares, transfer all
            withdrawPerPrice(_depositor, _balance, true);
            withdrawAmount = _balance;
        }
        lastActionBalance = balance();
        
        return withdrawAmount;
    }
    
    function updateTokenPrices() internal {
        for(uint256 i = 0; i < tokenList.length; i++){
            uint256 price = oracleContract.getPrice(address(tokenList[i].token));
            if(price > 0){
                tokenList[i].price = price;
            }
        }        
    }
    
    // This will withdraw the tokens from the contract based on their price, from lowest price to highest
    function withdrawPerPrice(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
        uint256 length = tokenList.length;
        if(_takeAll == true){
            for(uint256 i = 0; i < length; i++){
                if(tokenList[i].token.balanceOf(address(this)) > 0){
                    tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this)));
                }
            }
            return;
        }
        bool[4] memory done;
        uint256 targetID = 0;
        uint256 targetPrice = 0;
        updateTokenPrices(); // Update the prices based on an off-chain Oracle
        for(uint256 i = 0; i < length; i++){
            
            targetPrice = 0; // Reset the target price
            // Find the lowest priced token to withdraw
            for(uint256 i2 = 0; i2 < length; i2++){
                if(done[i2] == false){
                    uint256 _price = tokenList[i2].price;
                    if(targetPrice == 0 || _price <= targetPrice){
                        targetPrice = _price;
                        targetID = i2;
                    }
                }
            }
            done[targetID] = true;
            
            // Determine the balance left
            uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
            if(_normalizedBalance <= _withdrawAmount){
                // Withdraw the entire balance of this token
                if(_normalizedBalance > 0){
                    _withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
                    tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));                    
                }
            }else{
                // Withdraw a partial amount of this token
                if(_withdrawAmount > 0){
                    // Convert the withdraw amount to the token's decimal amount
                    uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
                    _withdrawAmount = 0;
                    tokenList[targetID].token.safeTransfer(_receiver, _balance);
                }
                break; // Nothing more to withdraw
            }
        }
    }
    
    function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
        // Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
        require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
        require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
        checkAndSwapTokens(true, _executor);
    }
    
    // Governance functions
    function governanceSwapTokens(bool _restrict) external onlyGovernance {
        // This is function that force trade tokens at anytime. It can only be called by governance
        checkAndSwapTokens(_restrict, _msgSender());
    }
    
    // Timelock variables
    
    uint256 private _timelockStart; // The start of the timelock to change governance variables
    uint256 private _timelockType; // The function that needs to be changed
    uint256 constant _timelockDuration = 86400; // Timelock is 24 hours
    
    // Reusable timelock variables
    address private _timelock_address;
    uint256 private _timelock_data_1;
    
    modifier timelockConditionsMet(uint256 _type) {
        require(_timelockType == _type, "Timelock not acquired for this function");
        _timelockType = 0; // Reset the type once the timelock is used
        if(balance() > 0){ // Timelock only applies when balance exists
            require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
        }
        _;
    }
    
    // Change the owner of the token contract
    // --------------------
    function startGovernanceChange(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 1;
        _timelock_address = _address;       
    }
    
    function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
        transferGovernance(_timelock_address);
    }
    // --------------------
    
    // Change the treasury address
    // --------------------
    function startChangeTreasury(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 2;
        _timelock_address = _address;
    }
    
    function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
        treasuryAddress = _timelock_address;
    }
    // --------------------
    
    // Change the percent going to depositors for WETH
    // --------------------
    function startChangeDepositorPercent(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 3;
        _timelock_data_1 = _percent;
    }
    
    function finishChangeDepositorPercent() external onlyGovernance timelockConditionsMet(3) {
        percentDepositor = _timelock_data_1;
    }
    // --------------------
    
    // Change the staking address
    // --------------------
    function startChangeStakingPool(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 4;
        _timelock_address = _address;
    }
    
    function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(4) {
        stakingAddress = _timelock_address;
    }
    // --------------------
    
    // Change the zsToken address
    // --------------------
    function startChangeZSToken(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 5;
        _timelock_address = _address;
    }
    
    function finishChangeZSToken() external onlyGovernance timelockConditionsMet(5) {
        zsTokenAddress = _timelock_address;
    }
    // --------------------
    
    // Change the percent going to stakers for WETH
    // --------------------
    function startChangeStakersPercent(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 6;
        _timelock_data_1 = _percent;
    }
    
    function finishChangeStakersPercent() external onlyGovernance timelockConditionsMet(6) {
        percentStakers = _timelock_data_1;
    }
    // --------------------
    
    // Change the percent sold of each token
    // --------------------
    function startChangePercentSold(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 7;
        _timelock_data_1 = _percent;
    }
    
    function finishChangePercentSold() external onlyGovernance timelockConditionsMet(7) {
        percentSell = _timelock_data_1;
    }
    // --------------------
    
    // Change the price oracle contract used, in case of upgrades
    // --------------------
    function startChangePriceOracle(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 8;
        _timelock_address = _address;
    }
    
    function finishChangePriceOracle() external onlyGovernance timelockConditionsMet(8) {
        oracleContract = StabilizePriceOracle(_timelock_address);
    }
    // --------------------
    
    // Change the minimum reserve
    // --------------------
    function startChangeMinReserve(uint256 _reserve) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 9;
        _timelock_data_1 = _reserve;
    }
    
    function finishChangeMinReserve() external onlyGovernance timelockConditionsMet(9) {
        minReserve = _timelock_data_1;
    }
    // --------------------

    // Change the percent that goes to the executor for non-depositors profit
    // --------------------
    function startChangePercentExecutor(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 10;
        _timelock_data_1 = _percent;
    }
    
    function finishChangePercentExecutor() external onlyGovernance timelockConditionsMet(10) {
        percentExecutor = _timelock_data_1;
    }
    // --------------------
    
    // Change the amount of seconds before trading
    // --------------------
    function startChangeTradeWaitTime(uint256 _seconds) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 11;
        _timelock_data_1 = _seconds;
    }
    
    function finishChangeTradeWaitTime() external onlyGovernance timelockConditionsMet(11) {
        secondsBeforeTrade = _timelock_data_1;
    }
    // --------------------
    
    // Change percent of balance to trigger trade
    // --------------------
    function startChangePercentTradeTrigger(uint256 _percent) external onlyGovernance {
        require(_percent <= 100000,"Percent cannot be greater than 100%");
        _timelockStart = now;
        _timelockType = 12;
        _timelock_data_1 = _percent;
    }
    
    function finishChangePercentTradeTrigger() external onlyGovernance timelockConditionsMet(12) {
        percentTradeTrigger = _timelock_data_1;
    }
    // --------------------

    // Change the minimum trade size before splitting, otherwise sells entire amount
    // --------------------
    function startChangeMinTradeSplit(uint256 _split) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 13;
        _timelock_data_1 = _split;
    }
    
    function finishChangeMinTradeSplit() external onlyGovernance timelockConditionsMet(13) {
        minTradeSplit = _timelock_data_1;
    }
    // --------------------
}
function startChangeTradeWaitTime(uint256 _seconds) external onlyGovernance {
    _timelockStart = now;
    _timelockType = 11;
    _timelock_data_1 = _seconds;
}

// --------------------
// Change the amount of seconds before trading
// --------------------