contract KunBptMining is LPTokenWrapper, IRewardDistributionRecipient {
    using SafeERC20 for IERC20;

    IERC20 public kun;

    uint256 public DURATION = 7 days;
    uint256 public withdrawDelay = 1 days;

    uint256 public starttime = 1603456200; //utc+8 2020/10/23 20:30:00
    uint256 public periodFinish = 0;
    uint256 public rewardRate = 0;
    uint256 public lastUpdateTime;
    uint256 public rewardPerTokenStored;

    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    event RewardAdded(uint256 reward);
    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);
    event ClaimedTokens(address token, address owner, uint256 balance);

    constructor (uint256 _starttime, address _kun, address _bpt) public {
        starttime = _starttime;
        kun = IERC20(_kun);
        y = IERC20(_bpt);
        
        lastUpdateTime = starttime;
    }

    function setKun(address _kun) external onlyOwner {
        require(_kun != address(y), "change kun to y is forbidden");
        kun = IERC20(_kun);
    }

    function setLp(address _lp) external onlyOwner {
        setY(_lp);
    }

    function setDuration(uint256 _duration) external onlyOwner {
        DURATION = _duration;
    }

    function setStarttime(uint256 _starttime) external onlyOwner {
        starttime = _starttime;
    }

    function setWithdrawDelay(uint256 _withdrawDelay) external onlyOwner {
        withdrawDelay = _withdrawDelay;
    }

    //更新用户所获得的收益和用户保存的每个质押token获取的奖励数
    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = lastTimeRewardApplicable();
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }

    function lastTimeRewardApplicable() public view returns (uint256) {
        return Math.min(block.timestamp, periodFinish);
    }

    function rewardPerToken() public view returns (uint256) {
        if (totalSupply() == 0) {
            return rewardPerTokenStored;//初始为0
        }

        return 
            rewardPerTokenStored.add(
                lastTimeRewardApplicable()
                    .sub(lastUpdateTime)
                    .mul(rewardRate)
                    .mul(1e18)
                    .div(totalSupply())
            );
    }

    function earned(address account) public view returns (uint256) {
        return
            balanceOf(account)
                .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                .div(1e18)
                .add(rewards[account]);
    }

    // stake visibility is public as overriding LPTokenWrapper's stake() function
    function stake(uint256 amount) public override updateReward(msg.sender) checkStart {
        require(amount > 0, "Cannot stake 0");
        super.stake(amount);
        emit Staked(msg.sender, amount);
    }

    function withdraw(uint256 amount) public override updateReward(msg.sender) checkStart {
        require(amount > 0, "Cannot withdraw 0");
        super.withdraw(amount);
        emit Withdrawn(msg.sender, amount);
    }

    function exit() external {
        withdraw(balanceOf(msg.sender));
        getReward();
    }

    //取回截止目前所获得的收益
    function getReward() public updateReward(msg.sender) checkRewardStart {
        uint256 reward = earned(msg.sender);
        if (reward > 0) {
            rewards[msg.sender] = 0;
            IMintable(address(kun)).mint(msg.sender, reward);
            emit RewardPaid(msg.sender, reward);
        }
    }

    modifier checkStart() {
        require(block.timestamp > starttime,"not start");
        _;
    }

    modifier checkRewardStart() {
        require(block.timestamp > starttime + withdrawDelay, "withdraw reward not start");
        _;
    }

    function notifyRewardAmount(uint256 reward)
        external override
        onlyRewardDistribution
        updateReward(address(0))
    {
        if (block.timestamp >= periodFinish) {
            rewardRate = reward.div(DURATION);
        } else {
            uint256 remaining = periodFinish.sub(block.timestamp);
            uint256 leftover = remaining.mul(rewardRate);
            rewardRate = reward.add(leftover).div(DURATION);
        }
        lastUpdateTime = block.timestamp;
        periodFinish = block.timestamp.add(DURATION);
        emit RewardAdded(reward);
    }
}
function getReward() public updateReward(msg.sender) checkRewardStart {
    uint256 reward = earned(msg.sender);
    if (reward > 0) {
        rewards[msg.sender] = 0;
        IMintable(address(kun)).mint(msg.sender, reward);
        emit RewardPaid(msg.sender, reward);
    }
}

//取回截止目前所获得的收益