contract BCCStaking is Ownable {
    
    // Modifiers
    
    modifier eoaOnly {
        require(msg.sender == tx.origin);
        _;
    }
    
    modifier whenNotPaused {
        require((!paused) || (msg.sender == owner()), 'The contract is paused!');
        _;
    }
    
    
    // Events
    
    event Staked(address indexed from, uint indexed tokenId, uint timestamp);
    event Unstaked(address indexed from, uint indexed tokenId, uint timestamp);
    event RewardChanged(uint oldReward, uint newReward, uint timestamp);
    
    
    // Storage Variables
    
    uint oldBaseReward;
    uint baseRewardPerSecond;
    uint rewardChangedAt;
    
    mapping(uint => address) public ownerOf;
    mapping(address => uint) public lastClaimOfAccount;
    mapping(address => uint[]) public addressToOwnedTokens;
    
    bool public paused = false;
    
    IERC721Enumerable nftContract;
    IERC20 bccContract;
    
    
    // Constructor
    
    constructor(IERC721Enumerable nftContract_, IERC20 bccContract_, uint baseRewardPerDay_, bool paused_) {
        bccContract = bccContract_;
        nftContract = nftContract_;
        paused = paused_;
        baseRewardPerSecond = ((baseRewardPerDay_ * 1e18) / 1 days) + 1;
    }
    
    
    // External functions
    
    function stakeAndUnstakeMultiple(uint[] memory stakeTokenIds, uint[] memory unstakeTokenIds) whenNotPaused eoaOnly external {
        require(nftContract.isApprovedForAll(msg.sender,address(this)),"Approve the contract to transfer your tokens first!");
        claimAll();
        for(uint i = 0; i < stakeTokenIds.length; i++) {
            stake(stakeTokenIds[i]);
        }
        for(uint i = 0; i < unstakeTokenIds.length; i++) {
            unstake(unstakeTokenIds[i]);
        }
    }
    
    function stakeMultiple(uint[] memory tokenIds) whenNotPaused eoaOnly external {
        require(nftContract.isApprovedForAll(msg.sender,address(this)),"Approve the contract to transfer your tokens first!");
        claimAll();
        for(uint i = 0; i < tokenIds.length; i++) {
            stake(tokenIds[i]);
        }
        
    }
    
    function unstakeMultiple(uint[] memory tokenIds) whenNotPaused eoaOnly external {
        claimAll();
        for(uint i = 0; i < tokenIds.length; i++) {
            unstake(tokenIds[i]);
        }
    }
    
    function claimAll() whenNotPaused eoaOnly public {
        uint reward = getClaimAmountOfAccount(msg.sender);
        if(reward > 0) {
            bccContract.transfer(msg.sender,reward);
        }
        lastClaimOfAccount[msg.sender] = block.timestamp;
    }
    
    
    // View Only
    
    function getTokensOfAccount(address account) external view returns(uint[] memory tokens) {
        return addressToOwnedTokens[account];
    }
    
    function getClaimAmountOfAccount(address account) public view returns(uint total) {
        uint tokens = addressToOwnedTokens[account].length;
        if(tokens == 0) {
            return 0;
        }
        uint rewardChangedAt_ = rewardChangedAt;
        uint lastClaim = lastClaimOfAccount[account];
        uint endTimestamp = block.timestamp;
        if(endTimestamp < rewardChangedAt_ || rewardChangedAt_ == 0) {
            return (((endTimestamp - lastClaim) * ( rewardChangedAt_ == 0 ? baseRewardPerSecond : oldBaseReward)) * tokens);
        } else if(lastClaim > rewardChangedAt_) {
            return (((endTimestamp - lastClaim) * baseRewardPerSecond) * tokens);
        } else {
            return ((((endTimestamp - rewardChangedAt_) * baseRewardPerSecond) + ((rewardChangedAt_ - lastClaim) * oldBaseReward)) * tokens);
        }
    }
    
    function balanceOf(address account) public view returns(uint balance) {
        return addressToOwnedTokens[account].length;
    }
    
    function rewardPerDayPerToken() external view returns(uint rewardPerDay) {
        if(block.timestamp < rewardChangedAt || rewardChangedAt == 0)
            return ((rewardChangedAt == 0 ? baseRewardPerSecond : oldBaseReward) * 86400) / 1e18;
        return (baseRewardPerSecond * 86400) / 1e18;
    }
    
    
    // Internal
    
    function stake(uint tokenId) internal {
        nftContract.transferFrom(msg.sender,address(this),tokenId);
        ownerOf[tokenId] = msg.sender;
        addressToOwnedTokens[msg.sender].push(tokenId);
        emit Staked(msg.sender,tokenId,block.timestamp);
    }
    
    function unstake(uint tokenId) internal {
        require(ownerOf[tokenId] == msg.sender, "Only the owner of the token can withdraw it!");
        bool removed = false;
        uint[] memory ownedTokens = addressToOwnedTokens[msg.sender];
        for( uint i = 0; i < ownedTokens.length; i++) {
            if(ownedTokens[i] == tokenId) {
                addressToOwnedTokens[msg.sender][i] = ownedTokens[ownedTokens.length - 1];
                addressToOwnedTokens[msg.sender].pop();
                removed = true;
                break;
            }
        }
        require(removed, "Internal error!");
        ownerOf[tokenId] = address(0);
        nftContract.transferFrom(address(this),msg.sender,tokenId);
        emit Unstaked(msg.sender,tokenId,block.timestamp);
    }
    
    
    // Owner Only
    
    function setBaseRewardPerDay(uint perDay, uint timestamp) external onlyOwner {
        oldBaseReward = baseRewardPerSecond;
        rewardChangedAt = timestamp;
        baseRewardPerSecond = ((perDay * 1e18) / 1 days) + 1;
        emit RewardChanged(oldBaseReward, baseRewardPerSecond, timestamp);
    }
    
    function airdrop(address[] memory targets,uint[] memory amounts) external onlyOwner {
        require(targets.length == amounts.length, "Invalid data");
        for(uint i = 0; i < targets.length; i++) {
            bccContract.transfer(targets[i],amounts[i]);
        }
    }
    
    function setContracts(IERC721Enumerable nftContract_, IERC20 bccContract_) external onlyOwner {
        bccContract = bccContract_;
        nftContract = nftContract_;
    }
    
    function setPaused(bool state) external onlyOwner {
        paused = state;
    }
    
    function setEmergency(bool state) external onlyOwner {
        emergency = state;
    }
    
    function emergencyWithdrawBCCTokens(uint amount) external onlyOwner {
        bccContract.transfer(msg.sender,amount);
    }
    
    
    // Emergency Only
    
    bool internal emergency = false;
    
    function emergencyReturnToken(uint tokenId) eoaOnly external {
        require(emergency, 'You can only use this function in case of an emergency');
        unstake(tokenId); 
    }
    
}
function stakeAndUnstakeMultiple(uint[] memory stakeTokenIds, uint[] memory unstakeTokenIds) whenNotPaused eoaOnly external {
    require(nftContract.isApprovedForAll(msg.sender,address(this)),"Approve the contract to transfer your tokens first!");
    claimAll();
    for(uint i = 0; i < stakeTokenIds.length; i++) {
        stake(stakeTokenIds[i]);
    }
    for(uint i = 0; i < unstakeTokenIds.length; i++) {
        unstake(unstakeTokenIds[i]);
    }
}

// External functions