contract StabilizeStrategyPickleV1 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 percentLPDepositor = 50000; // 1000 = 1%, LP depositors earn 50% of all WETH produced, 100% of everything else
    uint256 public percentStakers = 50000; // 50% of non LP WETH goes to stakers, can be changed
    
    // Reward tokens tokens list
    address[] rewardTokenList;
    
    // Info of each user.
    struct UserInfo {
        uint256 depositTime; // The time the user made the last deposit, token share is calculated from this
    }
    
    mapping(address => UserInfo) private userInfo;
    uint256 public weightedAverageDepositTime = 0; // Average time to enter
    
    // Strategy specific variables
    uint256 private _totalBalancePTokens = 0; // The total amount of pTokens currently staked/stored in contract
    uint256 private _stakedPickle = 0; // The amount of pickles being staked
    address constant wethAddress = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    address constant pickleAddress = address(0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5);
    address constant pJarAddress = address(0x09FC573c502037B149ba87782ACC81cF093EC6ef); // Pickle jar address / pToken address
    address constant pFarmAddress = address(0xbD17B1ce622d73bD438b9E658acA5996dc394b0d); // Pickle farming contract aka MasterChef
    uint256 constant pTokenID = 12; // The location of the pToken in the pickle staking farm
    address constant pickleStakeAddress = address(0xa17a8883dA1aBd57c690DF9Ebf58fC194eDAb66F); // Pickle staking address
    uint256 constant minETH = 1000000000; // 0.000000001 ETH / 1 Gwei

    constructor(
        address _treasury,
        address _staking,
        address _zsToken
    ) public {
        treasuryAddress = _treasury;
        stakingAddress = _staking;
        zsTokenAddress = _zsToken;
        setupRewardTokens();
    }

    // Initialization functions
    
    function setupRewardTokens() internal {
        // Reward tokens
        rewardTokenList.push(address(0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852)); // Uniswap LP token for ETH/USDT
        rewardTokenList.push(pickleAddress); // Picke token
        rewardTokenList.push(wethAddress); // Wrapped Ether token
    }
    
    // Modifier
    modifier onlyZSToken() {
        require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
        _;
    }
    
    // Read functions
    
    function rewardTokensCount() external view returns (uint256) {
        return rewardTokenList.length;
    }
    
    function rewardTokenAddress(uint256 _pos) external view returns (address) {
        require(_pos < rewardTokenList.length,"No token at that position");
        return rewardTokenList[_pos];
    }
    
    function balance() external view returns (uint256) {
        return _totalBalancePTokens;
    }
    
    function pricePerToken() external view returns (uint256) {
        return PickleJar(pJarAddress).getRatio();
    }
    
    // Write functions
    
    function enter() external onlyZSToken {
        deposit(_msgSender());
    }
    
    function exit() external onlyZSToken {
        // The ZS token vault is removing all tokens from this strategy
        withdraw(_msgSender(),1,1);
    }
    
    function withdraw(address payable _depositor, uint256 _share, uint256 _total) public onlyZSToken returns (uint256) {
        require(_totalBalancePTokens > 0, "There are no LP tokens in this strategy");
        // When a user withdraws, we need to pull the user's share out from all the contracts and split its tokens
        checkWETHAndPay(); // First check if we have unclaimed WETH and claim it
        
        // Next we need to calculate our percent of pTokens
        bool _takeAll = false;
        if(_share == _total){
            _takeAll = true; // Remove everything to this user
        }
        
        uint256 pTokenAmount = _totalBalancePTokens;
        if(_takeAll == false){
            pTokenAmount = _totalBalancePTokens.mul(_share).div(_total);
        }else{
            (pTokenAmount, ) = PickleFarm(pFarmAddress).userInfo(pTokenID, address(this)); // Get the total amount at the farm
            _totalBalancePTokens = pTokenAmount;
        }
        
        // Lower the amount of pTokens
         _totalBalancePTokens = _totalBalancePTokens.sub(pTokenAmount);

         // Now withdraw the pLP from Pickle Farm
        PickleFarm(pFarmAddress).withdraw(pTokenID, pTokenAmount); // This function also returns Pickle earned
        
        // Now exchange the pJar token for the LP token
        IERC20 _lpToken = IERC20(rewardTokenList[0]);
        uint256 lpWithdrawAmount = 0;
        if(_takeAll == false){
            uint256 _before = _lpToken.balanceOf(address(this));
            PickleJar(pJarAddress).withdraw(pTokenAmount);
            lpWithdrawAmount = _lpToken.balanceOf(address(this)).sub(_before);
        }else{
            PickleJar(pJarAddress).withdrawAll();
            lpWithdrawAmount = _lpToken.balanceOf(address(this)); // Get all LP tokens here
        }
        require(lpWithdrawAmount > 0,"Failed to withdraw from the Pickle Jar");

        // Transfer the accessory tokens
        transferAccessoryTokens(_depositor, _share, _total);
        
        // Now we withdraw the LP to the user
        _lpToken.safeTransfer(_depositor, lpWithdrawAmount);
        return lpWithdrawAmount;
    }
    
    function transferAccessoryTokens(address payable _depositor, uint256 _share, uint256 _total) internal {
        bool _takeAll = false;
        if(_share == _total){
            _takeAll = true;
        }
        if(_takeAll == false){
            // We need to now calculate the percent of accessory tokens going to this depositor
            // It is based on how long the depositor is in the contract and their share
            
            uint256 exitTime = now;
            uint256 enterTime = userInfo[_depositor].depositTime;
            if(userInfo[_depositor].depositTime == 0){ // User has never deposited into the contract at this address
                enterTime = now; // No access to pickle or weth reward
            }
            uint256 numerator = exitTime.sub(enterTime);
            uint256 denominator = exitTime.sub(weightedAverageDepositTime);
            uint256 timeShare = 0;
            if(numerator > denominator){
                // This user has been in the contract longer than the average, allow up to 100% of tokens based on share
                timeShare = divisionFactor; // 100%
            }else{
                // User has been in less than or equal to average, limit token amount based on that
                if(denominator > 0){
                    timeShare = numerator.mul(divisionFactor).div(denominator);
                }else{
                    timeShare = 0;
                }
            }
            
            // Now withdraw the tokens based on the timeshare and share
            IERC20 _token = IERC20(pickleAddress);
            uint256 _tokenBalance = _token.balanceOf(address(this)); // Get balance of pickle in contract not staked
            uint256 tokenWithdrawAmount = _tokenBalance.add(_stakedPickle).mul(_share).div(_total); // First based on our share %
            tokenWithdrawAmount = tokenWithdrawAmount.mul(timeShare).div(divisionFactor); // Then on time in contract
            if(tokenWithdrawAmount > _tokenBalance){
                // Must remove some from the staking pool to fill this amount
                uint256 _removeAmount = tokenWithdrawAmount.sub(_tokenBalance);
                _stakedPickle = _stakedPickle.sub(_removeAmount);
                PickleStake(pickleStakeAddress).withdraw(_removeAmount);
            }
            // Send the Pickle to the user
            if(tokenWithdrawAmount > 0){
                _token.safeTransfer(_depositor, tokenWithdrawAmount);
            }
            
            // Now do the same for WETH
            _token = IERC20(wethAddress);
            _tokenBalance = _token.balanceOf(address(this)); // Weth is just stored in this contract until removed
            tokenWithdrawAmount = _tokenBalance.mul(_share).div(_total); // First based on our share %
            tokenWithdrawAmount = tokenWithdrawAmount.mul(timeShare).div(divisionFactor); // Then on time in contract
            // Convert and send ETH to user
            if(tokenWithdrawAmount > 0){
                WrappedEther(wethAddress).withdraw(tokenWithdrawAmount); // This will send ETH to this contract and burn WETH
                // Now send the Ether to user
                _depositor.transfer(tokenWithdrawAmount); // Transfer has low gas allocation, preventing re-entrancy
            }
        }else{
            // Just pull all pickle and all WETH
            if(_stakedPickle > 0){
                PickleStake(pickleStakeAddress).exit(); // Will pull all pickle and all WETH (should be near empty)
                _stakedPickle = 0;
            }
            IERC20 _token = IERC20(pickleAddress);
            if( _token.balanceOf(address(this)) > 0){
                _token.safeTransfer(_depositor, _token.balanceOf(address(this)));
            }
            _token = IERC20(wethAddress);
            uint256 wethBalance = _token.balanceOf(address(this));
            if(wethBalance > 0){
                if(_depositor != zsTokenAddress){
                    WrappedEther(wethAddress).withdraw(wethBalance); // This will send ETH to this contract and burn WETH
                    _depositor.transfer(wethBalance);
                }else{
                    // Keep it as ERC20
                    _token.safeTransfer(_depositor, wethBalance);
                }                
            }
        }        
    }

    receive() external payable {
        // We need an anonymous fallback function to accept ether into this contract
    }
    
    function deposit(address _depositor) public onlyZSToken {
        // Only the ZS token can call the function
        
        // Get the balance of the reward token sent here
        IERC20 _token = IERC20(rewardTokenList[0]);
        uint256 _lpBalance = _token.balanceOf(address(this));
        
        // Now deposit it into the pickle jar
        _token.safeApprove(pJarAddress ,_lpBalance); // Approve for transfer
        PickleJar(pJarAddress).deposit(_lpBalance); // Send the LP, get the pLP
        IERC20 _pToken = IERC20(pJarAddress);
        uint256 _pBalance = _pToken.balanceOf(address(this));
        require(_pBalance > 0,"Failed to get pTokens from the Pickle Jar");
        
        // Calculate the new weighted average
        if(_depositor != zsTokenAddress){
            // Calculate the deposit time
            userInfo[_depositor].depositTime = now;
            
            weightedAverageDepositTime = weightedAverageDepositTime.mul(_totalBalancePTokens)
                                        .div(_pBalance.add(_totalBalancePTokens));
            
            weightedAverageDepositTime = userInfo[_depositor].depositTime.mul(_pBalance)
                                        .div(_pBalance.add(_totalBalancePTokens))
                                        .add(weightedAverageDepositTime);
        }
        
        // Now deposit these tokens into the farm contract
        _pToken.safeApprove(pFarmAddress, _pBalance); // Approve for transfer
        PickleFarm(pFarmAddress).deposit(pTokenID, _pBalance); // This function also returns Pickle earned
        _totalBalancePTokens += _pBalance; // Add to our pTokens accounted for
        
        // Now check to see if we should claim and stake pickle
        checkPickleAndStake();
        
        // Now check to see if we should claim and payout WETH
        checkWETHAndPay();
    }
    
    function checkPickleAndStake() internal {
        // Check if we have pickle in this contract then stake if we do
        IERC20 _pickle = IERC20(pickleAddress);
        uint256 _balance = _pickle.balanceOf(address(this));
        if(_balance > 0){
            // We have pickle, let's stake it
            _pickle.safeApprove(pickleStakeAddress, _balance);
            PickleStake(pickleStakeAddress).stake(_balance);
            _stakedPickle += _balance;
        }
    }
    
    function checkWETHAndPay() internal {
        // Check if we have earned WETH from the staked pickle
        uint256 _balance = PickleStake(pickleStakeAddress).earned(address(this)); // This will return the WETH earned balance
        if(_balance > minETH){
            // Claim the reward and split it between the depositors, treasury and stakers
            IERC20 _token = IERC20(wethAddress);
            uint256 _before = _token.balanceOf(address(this));
            PickleStake(pickleStakeAddress).getReward(); // Pull the WETH from the staking address
            uint256 amount = _token.balanceOf(address(this)).sub(_before);
            require(amount > 0,"Pickle staking should have returned some WETH");
            uint256 depositorsAmount = amount.mul(percentLPDepositor).div(divisionFactor); // This amount remains in contract
            uint256 holdersAmount = amount.sub(depositorsAmount);
            uint256 stakersAmount = holdersAmount.mul(percentStakers).div(divisionFactor);
            uint256 treasuryAmount = holdersAmount.sub(stakersAmount);
            if(treasuryAmount > 0){
                _token.safeTransfer(treasuryAddress, treasuryAmount);
            }
            if(stakersAmount > 0){
                _token.safeTransfer(stakingAddress, stakersAmount);
                StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
            }
        }
    }
    
    
    // Governance functions
    // 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(_totalBalancePTokens > 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) {
        percentLPDepositor = _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;
    }
    // --------------------
}
function setupRewardTokens() internal {
    // Reward tokens
    rewardTokenList.push(address(0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852)); // Uniswap LP token for ETH/USDT
    rewardTokenList.push(pickleAddress); // Picke token
    rewardTokenList.push(wethAddress); // Wrapped Ether token
}

// Initialization functions