contract YFDMaster is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // Info of each user.
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. See explanation below.
        //
        // We do some fancy math here. Basically, any point in time, the amount of YFDs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accYfdPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accYfdPerShare` (and `lastRewardBlock`) gets updated.
        //   2. User receives the pending reward sent to his/her address.
        //   3. User's `amount` gets updated.
        //   4. User's `rewardDebt` gets updated.
    }

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

    mapping (address => uint256) public stableCoins; //store precision
    mapping (address=>mapping(address=>uint256)) public balances;

    address[] public stableCoinAddress;

    // The YFD TOKEN!
    YFDToken public YFD;
    // Dev address.
    address public devaddr;
    // Block number when bonus YFD period ends.
    uint256 public bonusEndBlock;
    // YFD tokens created per block.
    uint256 public yfdPerBlock;
    // Bonus muliplier for early YFD makers.
    uint256 public constant BONUS_MULTIPLIER = 1.5 ether;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigratorChef public migrator;

    // 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 = 0;
    // The block number when YFD mining starts.
    uint256 public startBlock;
    uint256 public cycleEndBlock;

    bool public ifInited=false;

    bool public ifFinishedFirstBatchPool=false;

    //which pool is the vote pool for dao vote
    uint256 daoPoolPid=uint256(-1);

    address YFDDAOAddress=address(0x0);
    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(
        YFDToken _yfd,
        address _devaddr,
        uint256 _yfdPerBlock
    ) public {
        YFD = _yfd;
        devaddr = _devaddr;
        yfdPerBlock = _yfdPerBlock;
        totalAllocPoint=100000;
    }

    modifier checkIfContract() {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(caller()) }
        require((codehash != accountHash && codehash != 0x0)==false,"forbid contract call");         
        _;
    }
    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    function finishFirstBatchPool()public onlyOwner{
        require(poolInfo.length==9);
        ifFinishedFirstBatchPool=true;
    }
    //only can do once
    function InitPool(uint256 _startBlock,uint256 _bonusBlock)public onlyOwner {
        require(ifInited==false,"have inited");

        address usdt=address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
        address usdc=address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
        address tusd=address(0x0000000000085d4780B73119b644AE5ecd22b376);
        address dai=address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
        bonusEndBlock = _startBlock+_bonusBlock;
        startBlock = _startBlock;
        cycleEndBlock=startBlock+264096;

        stableCoins[usdt]=1000000000000;
        stableCoins[usdc]=1000000000000;
        stableCoins[tusd]=1;
        stableCoins[dai]=1;
        stableCoinAddress.push(usdt);
        stableCoinAddress.push(usdc);
        stableCoinAddress.push(tusd);
        stableCoinAddress.push(dai);
        
        add(10000,IERC20(address(0x0)),true);
        ifInited=true;
    }
    function setDaoAddress(address _newYFDDAOAddress)public onlyOwner{
        YFDDAOAddress=_newYFDDAOAddress;
    }
    function setDaoPoolPid(uint _newDaoPoolpid)public onlyOwner{
        daoPoolPid=_newDaoPoolpid;
    }
    // Halve will not occur, if no one calls after Halve.
    // The first caller after halving will get more rewards
    function getSetPerBlockReward(uint256 _blockNo) internal returns (uint256){
        if(_blockNo>=cycleEndBlock){
            yfdPerBlock=yfdPerBlock.div(2);
            //If all one cycle no one call this, a bug will occur,
            cycleEndBlock+=264096;//no need to check for overflow
        }
        return yfdPerBlock;
    }

    // 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();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        if(ifFinishedFirstBatchPool)
            totalAllocPoint = totalAllocPoint.add(_allocPoint);

        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accYfdPerShare: 0,
            total_deposit:0
        }));
    }
    function adds(uint256[] memory _allocPoint, IERC20 [] memory _lpToken) public onlyOwner {
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        require(_allocPoint.length==_lpToken.length);
        for(uint256 i=0;i<_allocPoint.length;i++){
            if(ifFinishedFirstBatchPool)
                totalAllocPoint = totalAllocPoint.add(_allocPoint[i]);
            poolInfo.push(PoolInfo({
                lpToken: _lpToken[i],
                allocPoint: _allocPoint[i],
                lastRewardBlock: lastRewardBlock,
                accYfdPerShare: 0,
                total_deposit:0
            }));
        }
    }
    // Update the given pool's YFD 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;
    }

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigratorChef _migrator) public onlyOwner {
        migrator = _migrator;
    }

    // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
    function migrate(uint256 _pid) public {
        require(_pid!=0,"do not support stableCoin pool");
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_pid];
        IERC20 lpToken = pool.lpToken;
        uint256 bal = lpToken.balanceOf(address(this));
        lpToken.safeApprove(address(migrator), bal);
        IERC20 newLpToken = migrator.migrate(lpToken);
        require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
        pool.lpToken = newLpToken;
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        if (_to <= bonusEndBlock) {
            return _to.sub(_from).mul(BONUS_MULTIPLIER).div(1 ether);
        } else if (_from >= bonusEndBlock) {
            return _to.sub(_from);
        } else {
            return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER.div(1 ether)).add(
                _to.sub(bonusEndBlock)
            );
        }
    }

    // View function to see pending YFDs on frontend.
    function pendingYfd(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accYfdPerShare = pool.accYfdPerShare;
        if (block.number > pool.lastRewardBlock && pool.total_deposit != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 yfdReward = multiplier.mul(yfdPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accYfdPerShare = accYfdPerShare.add(yfdReward.mul(1e12).div(pool.total_deposit));
        }
        return user.amount.mul(accYfdPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward vairables 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 = pool.total_deposit;
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 yfdReward = multiplier.mul(getSetPerBlockReward(block.number)).mul(pool.allocPoint).div(totalAllocPoint);
        YFD.mint(devaddr, yfdReward.div(10));
        YFD.mint(address(this), yfdReward);
        pool.accYfdPerShare = pool.accYfdPerShare.add(yfdReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to YFDMaster for YFD allocation.
    function deposit(uint256 _pid, uint256 _amount,uint256 _daoData) public checkIfContract{
        require(_pid!=0,"");//can not withdraw stable coin by this function
        _deposit(_pid,_amount,IERC20(address(0x0)), _daoData);
    }

    function depositStable(address _coinAddress,uint256 _amount)public checkIfContract{

        require(stableCoins[_coinAddress]>0,"not stable coin");
        balances[_coinAddress][msg.sender]=balances[_coinAddress][msg.sender].add(_amount);
        _deposit(0,_amount.mul(stableCoins[_coinAddress]),IERC20(_coinAddress),0);
    }

    function _deposit(uint256 _pid, uint256 _amount,IERC20 stableCoin,uint256 _daoData) internal {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accYfdPerShare).div(1e12).sub(user.rewardDebt);
            safeYfdTransfer(msg.sender, pending);
        }
        if(address(stableCoin)==address(0x0))
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        else
            stableCoin.safeTransferFrom(address(msg.sender), address(this), _amount/stableCoins[address(stableCoin)]);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accYfdPerShare).div(1e12);
        pool.total_deposit=pool.total_deposit.add(_amount);
        if(YFDDAOAddress!=address(0x0)&&daoPoolPid==_pid)
            IYFDDAO(YFDDAOAddress).handleDeposit(msg.sender,_amount,_daoData);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from YFDMaster.
    function withdraw(uint256 _pid, uint256 _amount,uint256 _daoData) public checkIfContract {
        require(_pid!=0,"");//can not withdraw stable coin by this function
        _withdraw(_pid,_amount,IERC20(0x0),_daoData);
    }

    function withdrawStable(address _coinAddress,uint256 _amount)public checkIfContract{

        require(stableCoins[_coinAddress]>0,"not stable coin");
        balances[_coinAddress][msg.sender]=balances[_coinAddress][msg.sender].sub(_amount);
        _withdraw(0,_amount.mul(stableCoins[_coinAddress]),IERC20(address(_coinAddress)),0);

    }

    function _withdraw(uint256 _pid, uint256 _amount,IERC20 stableCoin,uint256 _daoData) internal {
        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.accYfdPerShare).div(1e12).sub(user.rewardDebt);
        safeYfdTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accYfdPerShare).div(1e12);
        if(address(stableCoin)==address(0x0))
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        else
            stableCoin.safeTransfer(address(msg.sender), _amount/stableCoins[address(stableCoin)]);
        pool.total_deposit=pool.total_deposit.sub(_amount);
        if(YFDDAOAddress!=address(0x0)&&daoPoolPid==_pid)
            IYFDDAO(YFDDAOAddress).handleWithdraw(msg.sender,_amount,_daoData);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) public {
        require(_pid!=0,"");//can not withdraw stable coin by this function
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        pool.lpToken.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

    // Safe YFD transfer function, just in case if rounding error causes pool to not have enough YFDs.
    function safeYfdTransfer(address _to, uint256 _amount) internal {
        uint256 yfdBal = YFD.balanceOf(address(this));
        if (_amount > yfdBal) {
            YFD.transfer(_to, yfdBal);
        } else {
            YFD.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
function deposit(uint256 _pid, uint256 _amount,uint256 _daoData) public checkIfContract{
    require(_pid!=0,"");//can not withdraw stable coin by this function
    _deposit(_pid,_amount,IERC20(address(0x0)), _daoData);
}

// Deposit LP tokens to YFDMaster for YFD allocation.