contract zsToken is ERC20("Stabilize Strategy BAC-MIC-Seigniorage ", "zs-BMSGR"), Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Variables
    uint256 constant divisionFactor = 100000;
    
    // There are no fees to deposit and withdraw from the zs-Tokens
    
    // Info of each user.
    struct UserInfo {
        uint256 depositTime; // The time the user made the last deposit
        uint256 shareEstimate;
    }
    
    mapping(address => UserInfo) private userInfo;
    
    // Token information
    // This wrapped token accepts multiple sgr coins
    // BAC, MIC
    struct TokenInfo {
        IERC20 token; // Reference of token
        uint256 decimals; // Decimals of token
    }
    
    TokenInfo[] private tokenList; // An array of tokens accepted as deposits
    address private _underlyingPriceAsset; // Token from which the price is derived for STBZ staking
    bool public depositsOpen = true; // Governance can open or close deposits without timelock, cannot block withdrawals
    
    // Strategy information
    StabilizeStrategy private currentStrategy; // This will be the contract for the strategy
    address private _pendingStrategy;
    
    // Events
    event Wrapped(address indexed user, uint256 amount);
    event Unwrapped(address indexed user, uint256 amount);

    constructor (address _priceAsset) public {
        _underlyingPriceAsset = _priceAsset;
        setupWithdrawTokens();
    }
    
    function setupWithdrawTokens() internal {
        // Start with BAC
        IERC20 _token = IERC20(address(0x3449FC1Cd036255BA1EB19d65fF4BA2b8903A69a));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals()
            })
        );   
        
        // MIC
        _token = IERC20(address(0x368B3a58B5f49392e5C9E4C998cb0bB966752E51));
        tokenList.push(
            TokenInfo({
                token: _token,
                decimals: _token.decimals()
            })
        );
    }
    
    function getCurrentStrategy() external view returns (address) {
        return address(currentStrategy);
    }
    
    function getPendingStrategy() external view returns (address) {
        return _pendingStrategy;
    }

    function underlyingAsset() public view returns (address) {
        // Can be used if staking in the STBZ pool
        return address(_underlyingPriceAsset);
    }
    
    function underlyingDepositAssets() public view returns (address, address, address) {
        // Returns all addresses accepted by this token vault
        return (address(tokenList[0].token), address(tokenList[1].token), address(tokenList[2].token));
    }
    
    function pricePerToken() public view returns (uint256) {
        if(totalSupply() == 0){
            return 1e18; // Shown in Wei units
        }else{
            return uint256(1e18).mul(valueOfVaultAndStrategy()).div(totalSupply());      
        }
    }
    
    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 valueOfVaultAndStrategy() public view returns (uint256) { // The total value of the tokens
        uint256 balance = getNormalizedTotalBalance(address(this)); // Get tokens stored in this contract
        if(currentStrategy != StabilizeStrategy(address(0))){
            balance += currentStrategy.balance(); // And tokens stored at the strategy
        }
        return balance;
    }
    
    function withdrawTokenReserves() public view returns (address, uint256) {
        // This function will return the address and amount of the token with the highest balance
        if(currentStrategy != StabilizeStrategy(address(0))){
            return currentStrategy.withdrawTokenReserves();
        }else{
            uint256 length = tokenList.length;
            uint256 targetID = 0;
            uint256 targetNormBalance = 0;
            for(uint256 i = 0; i < length; i++){
                uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
                if(_normBal > 0){
                    if(targetNormBalance == 0 || _normBal >= targetNormBalance){
                        targetNormBalance = _normBal;
                        targetID = i;
                    }
                }
            }
            if(targetNormBalance > 0){
                return (address(tokenList[targetID].token), tokenList[targetID].token.balanceOf(address(this)));
            }else{
                return (address(0), 0); // No balance
            }
        }
    }
    
    
    // Now handle deposits into the strategy
    function deposit(uint256 amount, uint256 _tokenID) public nonReentrant {
        uint256 total = valueOfVaultAndStrategy(); // Get token equivalent at strategy and here if applicable
        
        require(depositsOpen == true, "Deposits have been suspended, but you can still withdraw");
        require(currentStrategy != StabilizeStrategy(address(0)),"No strategy contract has been selected yet");
        require(_tokenID < tokenList.length, "Token ID is outside range of tokens in contract");
        
        IERC20 _token = tokenList[_tokenID].token; // Trusted tokens
        uint256 _before = _token.balanceOf(address(this));
        _token.safeTransferFrom(_msgSender(), address(this), amount); // Transfer token to this address
        amount = _token.balanceOf(address(this)).sub(_before); // Some tokens lose amount (transfer fee) upon transfer
        require(amount > 0, "Cannot deposit 0");
        bool nonContract = false;
        if(tx.origin == _msgSender()){
            nonContract = true; // The sender is not a contract
        }
        uint256 _strategyBalance = currentStrategy.balance(); // Will get the balance of the value of the main tokens at the strategy
        // Now call the strategy to deposit
        pushTokensToStrategy(); // Push any strategy tokens here into the strategy
        currentStrategy.deposit(nonContract); // Activate strategy deposit
        require(currentStrategy.balance() > _strategyBalance, "No change in strategy balance"); // Balance should increase
        uint256 normalizedAmount = amount.mul(1e18).div(10**tokenList[_tokenID].decimals); // Make sure everything is same units
        uint256 mintAmount = normalizedAmount;
        if(totalSupply() > 0){
            // There is already a balance here, calculate our share
            mintAmount = normalizedAmount.mul(totalSupply()).div(total); // Our share of the total
        }
        _mint(_msgSender(),mintAmount); // Now mint new zs-token to the depositor
        
        // Add the user information
        userInfo[_msgSender()].depositTime = now;
        userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.add(mintAmount);

        emit Wrapped(_msgSender(), amount);
    }
    
    function redeem(uint256 share) public nonReentrant {
        // Essentially withdraw our equivalent share of the pool based on share value
        // Users cannot choose which token they get. They get the largest quantity coin up to the lowest quantity
        require(share > 0, "Cannot withdraw 0");
        require(totalSupply() > 0, "No value redeemable");
        uint256 tokenTotal = totalSupply();
        // Now burn the token
        _burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough
        
        bool nonContract = false;
        if(tx.origin == _msgSender()){
            nonContract = true; // The sender is not a contract, we will allow market sells and buys
        }else{
            // This is a contract redeeming
            require(userInfo[_msgSender()].depositTime < now && userInfo[_msgSender()].depositTime > 0, "Contract depositor cannot redeem in same transaction");
        }
        
        // Update user information
        if(share <= userInfo[_msgSender()].shareEstimate){
            userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.sub(share);
        }else{
            // Share is greater than our share estimate, can happen if tokens are transferred
            userInfo[_msgSender()].shareEstimate = 0;
            require(nonContract == true, "Contract depositors cannot take out more than what they put in");
        }

        uint256 withdrawAmount = 0;
        if(currentStrategy != StabilizeStrategy(address(0))){
            withdrawAmount = currentStrategy.withdraw(_msgSender(), share, tokenTotal, nonContract); // Returns the amount of underlying removed
            require(withdrawAmount > 0, "Failed to withdraw from the strategy");
        }else{
            // Pull directly from this contract the token amount in relation to the share if strategy not used
            if(share < tokenTotal){
                uint256 _balance = getNormalizedTotalBalance(address(this));
                uint256 _myBalance = _balance.mul(share).div(tokenTotal);
                withdrawPerBalance(_msgSender(), _myBalance, false); // This will withdraw based on token balanace
                withdrawAmount = _myBalance;
            }else{
                // We are all shares, transfer all
                uint256 _balance = getNormalizedTotalBalance(address(this));
                withdrawPerBalance(_msgSender(), _balance, true);
                withdrawAmount = _balance;
            }
        }
        
        emit Unwrapped(_msgSender(), withdrawAmount);
    }
    
    // This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
    function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
        uint256 length = tokenList.length;
        if(_takeAll == true){
            // Send the entire balance
            for(uint256 i = 0; i < length; i++){
                uint256 _bal = tokenList[i].token.balanceOf(address(this));
                if(_bal > 0){
                    tokenList[i].token.safeTransfer(_receiver, _bal);
                }
            }
            return;
        }
        bool[4] memory done;
        uint256 targetID = 0;
        uint256 targetNormBalance = 0;
        for(uint256 i = 0; i < length; i++){
            
            targetNormBalance = 0; // Reset the target balance
            // Find the highest balanced token to withdraw
            for(uint256 i2 = 0; i2 < length; i2++){
                if(done[i2] == false){
                    uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
                    if(targetNormBalance == 0 || _normBal >= targetNormBalance){
                        targetNormBalance = _normBal;
                        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
            }
        }
    }
    
    // Governance functions
    
    // Stop/start all deposits, no timelock required
    // --------------------
    function stopDeposits() external onlyGovernance {
        depositsOpen = false;
    }

    function startDeposits() external onlyGovernance {
        depositsOpen = true;
    }

    // A function used in case of strategy failure, possibly due to bug in the platform our strategy is using, governance can stop using it quick
    function emergencyStopStrategy() external onlyGovernance {
        depositsOpen = false;
        if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
            currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy 
        }
        currentStrategy = StabilizeStrategy(address(0));
        _timelockType = 0; // Prevent governance from changing to new strategy without timelock
    }

    // --------------------
    
    // 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;
    
    modifier timelockConditionsMet(uint256 _type) {
        require(_timelockType == _type, "Timelock not acquired for this function");
        _timelockType = 0; // Reset the type once the timelock is used
        if(totalSupply() > 0){
            // Timelock is only required after tokens exist
            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 startChangeStrategy(address _address) external onlyGovernance {
        _timelockStart = now;
        _timelockType = 2;
        _timelock_address = _address;
        _pendingStrategy = _address;
        if(totalSupply() == 0){
            // Can change strategy with one call in this case
            finishChangeStrategy();
        }
    }
    
    function finishChangeStrategy() public onlyGovernance timelockConditionsMet(2) {
        if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
            currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy 
        }
        currentStrategy = StabilizeStrategy(_timelock_address);
        if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
            pushTokensToStrategy(); // It will push any strategy reward tokens here to the new strategy
            currentStrategy.enter(); // Puts all the tokens and accessory tokens into the new strategy 
        }
        _pendingStrategy = address(0);
    }
    
    function pushTokensToStrategy() internal {
        uint256 tokenCount = currentStrategy.rewardTokensCount();
        for(uint256 i = 0; i < tokenCount; i++){
            IERC20 _token = IERC20(address(currentStrategy.rewardTokenAddress(i)));
            uint256 _balance = _token.balanceOf(address(this));
            if(_balance > 0){
                _token.safeTransfer(address(currentStrategy), _balance);
            }
        }
    }
    // --------------------

}
function startGovernanceChange(address _address) external onlyGovernance {
    _timelockStart = now;
    _timelockType = 1;
    _timelock_address = _address;       
}

// Change the owner of the token contract
// --------------------