contract ZEUSMain 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 ZEUSs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accZEUSPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accZEUSPerShare` (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 {
        IERC20 lpToken;           // Address of LP token contract.
        bool bChange;             // 
        bool bLock;               // 
        bool bDepositFee;          //
        uint256 depositMount;     // 
        uint256 changeMount;     // 
        uint256 allocPoint;       // How many allocation points assigned to this pool. ZEUSs to distribute per block.
        uint256 lastRewardBlock;  // Last block number that ZEUSs distribution occurs.
        uint256 accZEUSPerShare; // Accumulated ZEUSs per share, times 1e12. See below.
    }

    struct AreaInfo {
        uint256 totalAllocPoint;
        uint256 rate;
    }

    // The ZEUS TOKEN!
    ZEUSToken public zeus;
    // Dev address.
    address public devaddr;
    // min per block mint
    uint256 public minPerBlock;
    // ZEUS tokens created per block.
    uint256 public zeusPerBlock;
    uint256 public halfPeriod;
    uint256 public lockPeriods; // lock periods

    // 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;
    mapping (uint256 => PoolInfo[]) public poolInfo;
    // Info of each user that stakes LP tokens.
    //mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    mapping (uint256 => 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;
    AreaInfo[] public areaInfo;
    uint256 public totalRate = 0;

    // The block number when ZEUS mining starts.
    uint256 public startBlock;

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

    constructor(
        ZEUSToken _zeus,
        address _devaddr,
        uint256 _zeusPerBlock,
        uint256 _startBlock,
        uint256 _minPerBlock,
        uint256 _halfPeriod,
        uint256 _lockPeriods
    ) public {
        zeus = _zeus;
        devaddr = _devaddr;
        zeusPerBlock = _zeusPerBlock;
        minPerBlock = _minPerBlock;
        startBlock = _startBlock;
        halfPeriod = _halfPeriod;
        lockPeriods = _lockPeriods;
    }

    function buyBackToken(address payable buybackaddr) public onlyOwner {
        require(buybackaddr != address(0), "buy back is addr 0");
        buybackaddr.transfer(address(this).balance);
    }

    function areaLength() external view returns (uint256) {
        return areaInfo.length;
    }

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

    function addArea(uint256 _rate, bool _withUpdate) public onlyOwner {

        if (_withUpdate) {
            massUpdateAreas();
        }

        totalRate = totalRate.add(_rate);
        areaInfo.push(AreaInfo({
        totalAllocPoint: 0,
        rate: _rate
        }));
    }

    // 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 _aid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools(_aid);
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.add(_allocPoint);
        poolInfo[_aid].push(PoolInfo({
        lpToken: _lpToken,
        bChange: false,
        bLock: _bLock,
        bDepositFee: _bDepositFee,
        depositMount: _depositFee,
        changeMount: 0,
        allocPoint: _allocPoint,
        lastRewardBlock: lastRewardBlock,
        accZEUSPerShare: 0
        }));
    }

    function setArea(uint256 _aid, uint256 _rate, bool _withUpdate) public onlyOwner {

        if (_withUpdate) {
            massUpdateAreas();
        }

        totalRate = totalRate.sub(areaInfo[_aid].rate).add(_rate);
        areaInfo[_aid].rate = _rate;
    }

    // Update the given pool's zeus allocation point. Can only be called by the owner.
    function set(uint256 _aid, uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _bChange, uint256 _changeMount, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools(_aid);
        }
        areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(poolInfo[_aid][_pid].allocPoint).add(_allocPoint);
        poolInfo[_aid][_pid].allocPoint = _allocPoint;
        poolInfo[_aid][_pid].bChange = _bChange;
        poolInfo[_aid][_pid].bLock = _bLock;
        poolInfo[_aid][_pid].changeMount = _changeMount;
        poolInfo[_aid][_pid].bDepositFee = _bDepositFee;
        poolInfo[_aid][_pid].depositMount = _depositFee;
    }

    // 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 _aid, uint256 _pid) public {
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_aid][_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;
    }

    // Reduce by 50% per halfPeriod blocks.
    function getBlockReward(uint256 number) public view returns (uint256) {
        if (number < startBlock){
            return 0;
        }
        uint256 mintBlocks = number.sub(startBlock);

        uint256 exp = mintBlocks.div(halfPeriod);

        if (exp == 0) return 100000000000000000000;
        if (exp == 1) return 80000000000000000000;
        if (exp == 2) return 60000000000000000000;
        if (exp == 3) return 40000000000000000000;
        if (exp == 4) return 20000000000000000000;
        if (exp == 5) return 10000000000000000000;
        if (exp == 6) return 8000000000000000000;
        if (exp == 7) return 6000000000000000000;
        if (exp == 8) return 4000000000000000000;
        if (exp == 9) return 2000000000000000000;
        if (exp >= 10) return 1000000000000000000;

        return 0;
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {

        if(_from < startBlock){
            _from = startBlock;
        }
        if(_from >= _to){
            return 0;
        }

        uint256 blockReward1 = getBlockReward(_from);
        uint256 blockReward2 = getBlockReward(_to);
        uint256 blockGap = _to.sub(_from);
        if(blockReward1 != blockReward2){
            uint256 blocks2 = _to.mod(halfPeriod);
            uint256 blocks1 = blockGap.sub(blocks2);
            return blocks1.mul(blockReward1).add(blocks2.mul(blockReward2));
        }
        return blockGap.mul(blockReward1);

    }

    // View function to see pending ZEUSs on frontend.
    function pendingZEUS(uint256 _aid, uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_aid][_pid];
        UserInfo storage user = userInfo[_aid][_pid][_user];
        uint256 accZEUSPerShare = pool.accZEUSPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 ZEUSReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint);
            accZEUSPerShare = accZEUSPerShare.add((ZEUSReward.mul(1e12).div(lpSupply)).mul(areaInfo[_aid].rate).div(totalRate));
        }
        return user.amount.mul(accZEUSPerShare).div(1e12).sub(user.rewardDebt);
    }

    function massUpdateAreas() public {
        uint256 length = areaInfo.length;
        for (uint256 aid = 0; aid < length; ++aid) {
            massUpdatePools(aid);
        }
    }


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

    // Update reward variables of the given pool to be up-to-date.
    function updatePool(uint256 _aid, uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_aid][_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 zeusReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint);
        zeus.mint(devaddr, zeusReward.div(20));
        zeus.mint(address(this), zeusReward);
        pool.accZEUSPerShare = pool.accZEUSPerShare.add((zeusReward.mul(1e12).div(lpSupply)).mul(areaInfo[_aid].rate).div(totalRate));
        pool.lastRewardBlock = block.number;

    }

    // Deposit LP tokens to ZEUSMain for ZEUS allocation.
    function deposit(uint256 _aid, uint256 _pid, uint256 _amount) payable public {
        PoolInfo storage pool = poolInfo[_aid][_pid];
        UserInfo storage user = userInfo[_aid][_pid][msg.sender];

        if (_amount > 0){        
            require((pool.bDepositFee == false) || (pool.bDepositFee == true && msg.value == pool.depositMount), "deposit: not enough");
        }
        
        updatePool(_aid, _pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                safeZEUSTransfer(msg.sender, pending);
            }
        }
        else {
            if (pool.bChange == true)
            {
                pool.allocPoint += pool.changeMount;
                areaInfo[_aid].totalAllocPoint += pool.changeMount;
            }
        }
        if(_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12);
        emit Deposit(msg.sender, _aid, _pid, _amount);
    }

    // Withdraw LP tokens from ZEUSMain.
    function withdraw(uint256 _aid, uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_aid][_pid];
        UserInfo storage user = userInfo[_aid][_pid][msg.sender];
        require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock");
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_aid, _pid);
        uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeZEUSTransfer(msg.sender, pending);
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        if (user.amount == 0)
        {
            if (pool.bChange == true)
            {
                uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0;
                pool.allocPoint = pool.allocPoint.sub(changenum);
                areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum);
            }
        }
        user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12);
        emit Withdraw(msg.sender, _aid, _pid, _amount);
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _aid, uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_aid][_pid];
        UserInfo storage user = userInfo[_aid][_pid][msg.sender];

        require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock");

        pool.lpToken.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _aid, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
        if (pool.bChange == true)
        {
            uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0;
            pool.allocPoint = pool.allocPoint.sub(changenum);
            areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum);
        }

    }

    // Safe ZEUS transfer function, just in case if rounding error causes pool to not have enough ZEUSs.
    function safeZEUSTransfer(address _to, uint256 _amount) internal {
        uint256 ZEUSBal = zeus.balanceOf(address(this));
        if (_amount > ZEUSBal) {
            zeus.transfer(_to, ZEUSBal);
        } else {
            zeus.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
// ZEUSMain is the master of ZEUS. He can make ZEUS and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once ZEUS is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function migrate(uint256 _aid, uint256 _pid) public {
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_aid][_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;
    }
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.