contract GriffinMigrator 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 GRIFFINs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accGriffinPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accGriffinPerShare` (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.
    }

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

    // The GRIFFIN TOKEN!
    GriffinToken public griffin;
    // Dev address.
    address public devaddr;
    // Block number when bonus GRIFFIN period ends.
    // Dev fund (10%, initially)
    uint256 public devFundDivRate = 10;
    uint256 public bonusEndBlock;
    // GRIFFIN tokens created per block.
    uint256 public griffinPerBlock;
    // Bonus muliplier for early griffin makers.
    uint256 public bonusMultiplier = 10;

    // 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 GRIFFIN mining starts.
    uint256 public startBlock;

    //Crosschain migrator
    ICrossChainMigrator public crossChainMigrator;

    event Remove(address indexed user, uint256 indexed pid, uint256 amount);
    event Migrate(address indexed user, address indexed tokenA, address indexed tokenB, uint256 amountA, uint256 amountB);

    constructor(
        GriffinToken _griffin,
        address _devaddr,
        uint256 _griffinPerBlock,
        uint256 _startBlock,
        uint256 _bonusEndBlock,
        ICrossChainMigrator _crossChainMigrator
    ) public {
        griffin = _griffin;
        devaddr = _devaddr;
        griffinPerBlock = _griffinPerBlock;
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
        crossChainMigrator = _crossChainMigrator;
    }

    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, IUniswapV2Pair _lpToken, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accGriffinPerShare: 0
        }));
    }

    // Update the given pool's GRIFFIN 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;
    }

    //Migrate lp token from to another chain and another lp contract
    function migrateToOtherChain(uint256 _pid, uint256 _amount) external {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accGriffinPerShare).div(1e12).sub(user.rewardDebt);
            safeGriffinTransfer(msg.sender, pending);
        }
        //Remove liquidity
        pool.lpToken.transferFrom(address(msg.sender), address(pool.lpToken), _amount);
        address token0 = pool.lpToken.token0();
        address token1 = pool.lpToken.token1();
        (uint256 amount0, uint256 amount1) = pool.lpToken.burn(address(this));

        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accGriffinPerShare).div(1e12);

        //Call migrator other chain
        IERC20(token0).approve(address(crossChainMigrator), amount0);
        crossChainMigrator.relayTokens(token0, owner(), amount0);
        IERC20(token1).approve(address(crossChainMigrator), amount1);
        crossChainMigrator.relayTokens(token1, owner(), amount1);

        emit Migrate(msg.sender, token0, token1, amount0, amount1);
    }

    // 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(bonusMultiplier);
        } else if (_from >= bonusEndBlock) {
            return _to.sub(_from);
        } else {
            return bonusEndBlock.sub(_from).mul(bonusMultiplier).add(
                _to.sub(bonusEndBlock)
            );
        }
    }

    // Claim pending griffin that user has
    function claimPendingGriffin(uint256 _pid) external returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accGriffinPerShare).div(1e12).sub(user.rewardDebt);
        safeGriffinTransfer(msg.sender, pending);

        return pending;
    }

    // View function to see pending GRIFFINs on frontend.
    function pendingGriffin(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accGriffinPerShare = pool.accGriffinPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 griffinReward = multiplier.mul(griffinPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accGriffinPerShare = accGriffinPerShare.add(griffinReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accGriffinPerShare).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.lpToken.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 griffinReward = multiplier.mul(griffinPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        griffin.mint(devaddr, griffinReward.div(devFundDivRate));
        griffin.mint(address(this), griffinReward);
        pool.accGriffinPerShare = pool.accGriffinPerShare.add(griffinReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Remove liquidity on other chain, will remove griffin share user in this chain
    function removeFromOtherChain(uint256 _pid, uint256 _amount) public onlyOwner {
        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.accGriffinPerShare).div(1e12).sub(user.rewardDebt);
        safeGriffinTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accGriffinPerShare).div(1e12);
        emit Remove(msg.sender, _pid, _amount);
    }

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

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
    
    // **** Additional functions separate from the original Arimaspian contract ****
    function config(uint256 _griffinPerBlock, uint256 _bonusMultiplier, uint256 _bonusEndBlock) public onlyOwner {
        require(_griffinPerBlock > 0, "!griffinPerBlock-0");
        require(block.number > bonusEndBlock, "Still processing latest bonus");
        require(_bonusEndBlock >= bonusEndBlock, "Bonus will not start");
        massUpdatePools();
        griffinPerBlock = _griffinPerBlock;
        bonusMultiplier = _bonusMultiplier;
        bonusEndBlock = _bonusEndBlock;
    }

    function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner {
        require(_devFundDivRate > 0, "!devFundDivRate-0");
        devFundDivRate = _devFundDivRate;
    }

    function setGriffinPerBlock(uint256 _griffinPerBlock) public onlyOwner {
        require(_griffinPerBlock > 0, "!griffinPerBlock-0");
        
        griffinPerBlock = _griffinPerBlock;
    }

    function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
        require(block.number > bonusEndBlock, "Still processing latest bonus");
        bonusEndBlock = _bonusEndBlock;
    }
    
    function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
        require(block.number > bonusEndBlock, "Still processing latest bonus");
        bonusMultiplier = _bonusMultiplier;
    }
}
function dev(address _devaddr) public {
    require(msg.sender == devaddr, "dev: wut?");
    devaddr = _devaddr;
}

// Update dev address by the previous dev.