contract StakingCRC is Ownable {
    using SafeMath for uint256;

    // Info of each user.
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. See explanation below.        
    }

    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool. Shows to distribute per block.
        uint256 lastRewardBlock;  // Last block number that Shows distribution occurs.
        uint256 acccrcPerShare; // Accumulated Shows per share, times 1e12. See below.
    }

    // The crc TOKEN!
    IERC20 public crc;
    
    // crc tokens per block.
    uint256 public crcPerBlock;    

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that stakes LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    // Total allocation poitns. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoint;
    
    uint256 public maxStake;
    uint256 public totalStaked = 0;

    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);

    
    constructor() {
        crc = IERC20(0xC23fa49b581fFF9a3ea7E49D0504B06D07C6FF2a);
        crcPerBlock = 695 *10**18;
        maxStake = 2000000000000 *10**18;

        
        totalAllocPoint = totalAllocPoint.add(crcPerBlock);
        poolInfo.push(PoolInfo({
            lpToken: IERC20(0x7c4dD5a25da11DDC08014B8B2010a3894d3326F7), // cash Token
            allocPoint: crcPerBlock,
            lastRewardBlock: block.number,
            acccrcPerShare: 0
        }));

    }

    

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Add a new lp to the pool. Can only be called by the owner.
    // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
    function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: block.number,
            acccrcPerShare: 0
        }));
        
    }

    // Update the given pool's crc allocation point. Can only be called by the owner.
    function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
        poolInfo[_pid].allocPoint = _allocPoint;
        
    }


    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
        return _to.sub(_from);
    }

    // View function to see pending crc on frontend.
    function pendingcrc(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 acccrcPerShare = pool.acccrcPerShare;
        uint256 lpSupply;
        if(_pid==0)
        {
            lpSupply = totalStaked;
        } else {
            lpSupply = pool.lpToken.balanceOf(address(this));
        }
        
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 crcReward = multiplier.mul(crcPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            acccrcPerShare = acccrcPerShare.add(crcReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(acccrcPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward variables for all pools. Be careful of gas spending!
    function massUpdatePools() public {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            updatePool(pid);
        }
    }


    // Update reward variables of the given pool to be up-to-date.
    function updatePool(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        if (block.number <= pool.lastRewardBlock) {
            return;
        }
        uint256 lpSupply; 
        if (_pid == 0) {
            lpSupply = totalStaked;
        }
        else {
            lpSupply = pool.lpToken.balanceOf(address(this));
        } 
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 crcReward = multiplier.mul(crcPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        pool.acccrcPerShare = pool.acccrcPerShare.add(crcReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    function stake(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.acccrcPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                //safeCRCTransfer(msg.sender, pending);
                user.amount = user.amount.add(pending);
                totalStaked = totalStaked + pending;
                require(totalStaked <= maxStake, "staking pool reached max limit");
            }
        }
        if (_amount > 0) {
            pool.lpToken.transferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
            if(_pid == 0) {
                totalStaked = totalStaked + _amount;
                require(totalStaked <= maxStake, "staking pool reached max limit");
            }
        }
        user.rewardDebt = user.amount.mul(pool.acccrcPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    function unstake(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.acccrcPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeCRCTransfer(msg.sender, pending);
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.transfer(address(msg.sender), _amount);
            if(_pid == 0) {
                totalStaked = totalStaked - _amount;
            }
        }
        user.rewardDebt = user.amount.mul(pool.acccrcPerShare).div(1e12);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    function harvest(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.acccrcPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeCRCTransfer(msg.sender, pending);
            user.rewardDebt = user.amount.mul(pool.acccrcPerShare).div(1e12);
            emit Withdraw(msg.sender, _pid, pending);
        }
        
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        pool.lpToken.transfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

    // Safe crc transfer function, just in case if rounding error causes pool to not have enough Shows.
    function safeCRCTransfer(address _to, uint256 _amount) internal {
        uint256 balance = crc.balanceOf(address(this));
        crc.transfer(_to, _amount > balance ? balance : _amount);
    }

    function emergencyWithdrawCRC() public onlyOwner {
        uint256 balance = crc.balanceOf(address(this));
        crc.transfer(msg.sender, balance );
    }

    function emergencyWithdrawETH() public onlyOwner {
        uint256 Balance = address(this).balance;
        (bool succ, ) = msg.sender.call{value: Balance}("");
        require(succ, "withdraw not sent"); 
    }

    function setPerBlock(uint256 _perBlock) public onlyOwner {
        require(_perBlock > 0, "per block must be positive");
        crcPerBlock = _perBlock;
    }

    function setMaxStake(uint256 _maxStake) public onlyOwner {
        require(_maxStake > 0, "max Stake must be positive");
        maxStake = _maxStake;
    }
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
    if (_withUpdate) {
        massUpdatePools();
    }
    totalAllocPoint = totalAllocPoint.add(_allocPoint);
    poolInfo.push(PoolInfo({
        lpToken: _lpToken,
        allocPoint: _allocPoint,
        lastRewardBlock: block.number,
        acccrcPerShare: 0
    }));
        
}

// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.