contract Pill is IERC20, Auth, IERC721Receiver {
    using SafeMath for uint256;

    uint256 public constant MASK = type(uint128).max;
    address public WETH = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;
    address DEAD = 0x000000000000000000000000000000000000dEaD;
    address ZERO = 0x0000000000000000000000000000000000000000;
    address DEAD_NON_CHECKSUM = 0x000000000000000000000000000000000000dEaD;
    uint256 MAX_INT = 2**256 - 1;

    string constant _name = "$PILL";
    string constant _symbol = "$PILL";
    uint8 constant _decimals = 18;

    /// @notice Represents the deposit of an NFT
    struct Deposit {
      address owner;
      uint128 liquidity;
      address token0;
      address token1;
    }
    mapping(uint256 => Deposit) public deposits;

    uint256 public totalSupply;
    uint256 public _maxTxAmount = MAX_INT; // no limitation

    mapping (address => uint256) _balances;
    mapping (address => mapping (address => uint256)) _allowances;
    mapping (address => bool) public mintableAdmins;

    mapping (address => bool) isFeeExempt;
    mapping (address => bool) isTxLimitExempt;    

    uint256 liquidityFee = 300; // 3%
    uint256 buybackFee = 200; // 2%
    uint256 marketingFee = 300; // 3%
    uint256 totalFee = 800;
    uint256 feeDenominator = 10000;

    address public autoLiquidityReceiver;
    address public marketingFeeReceiver;

    uint256 targetLiquidity = 25;
    uint256 targetLiquidityDenominator = 100;

    IUniswapRouter public uniswapRouter;
    INonfungiblePositionManager public nonfungiblePositionManager;
    IERC20 public myWETH;
    ILPManager public lpManager;

    address public poolAddress;
    uint24 public swapFee = 3000;
    uint256 public tokenId; // for liquidity

    uint256 public launchedAt;
    uint256 public launchedAtTimestamp;

    uint256 buybackMultiplierNumerator = 200;
    uint256 buybackMultiplierDenominator = 100;
    uint256 buybackMultiplierTriggeredAt;
    uint256 buybackMultiplierLength = 30 minutes;

    bool public autoBuybackEnabled = false;
    mapping (address => bool) buyBacker;
    uint256 autoBuybackCap;
    uint256 autoBuybackAccumulator;
    uint256 autoBuybackAmount;
    uint256 autoBuybackBlockPeriod;
    uint256 autoBuybackBlockLast;

    bool public swapEnabled = true;
    uint256 public swapThreshold = 100 * (10**_decimals); // 100 tokens;
    bool inSwap;
    modifier swapping() { inSwap = true; _; inSwap = false; }
    modifier onlyMintableAdmins() {
        require(mintableAdmins[msg.sender], "You are not admin!"); _;
    }

    constructor (        
        address _uniswapRouter,
        INonfungiblePositionManager _nonfungiblePositionManager,
        address _lpManager
    ) Auth(msg.sender) {
        uniswapRouter = IUniswapRouter(_uniswapRouter);
        myWETH = IERC20(uniswapRouter.WETH9());
        lpManager = ILPManager(_lpManager);

        nonfungiblePositionManager = INonfungiblePositionManager(_nonfungiblePositionManager);        
        _allowances[address(this)][address(uniswapRouter)] = MAX_INT;
        WETH = uniswapRouter.WETH9();

        isFeeExempt[msg.sender] = true;
        isFeeExempt[_lpManager] = true;
        isFeeExempt[address(_nonfungiblePositionManager)] = true;
        isFeeExempt[_uniswapRouter] = true;

        isTxLimitExempt[msg.sender] = true;
        buyBacker[msg.sender] = true;

        autoLiquidityReceiver = msg.sender;
        marketingFeeReceiver = msg.sender;

        approve(_uniswapRouter, MAX_INT);                        
    }

    receive() external payable { }
    
    function decimals() external pure override returns (uint8) { return _decimals; }
    function symbol() external pure override returns (string memory) { return _symbol; }
    function name() external pure override returns (string memory) { return _name; }
    function getOwner() external view override returns (address) { return owner; }
    modifier onlyBuybacker() { require(buyBacker[msg.sender] == true, ""); _; }
    function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
    function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }

    function setRouter(IUniswapRouter _uniswapRouter) external onlyOwner {
      uniswapRouter = _uniswapRouter;
    }
    function setPositionManager(INonfungiblePositionManager _nonfungiblePositionManager) external onlyOwner {
      nonfungiblePositionManager = _nonfungiblePositionManager;
      _allowances[address(this)][address(_nonfungiblePositionManager)] = MAX_INT;
    }
    function setPoolAddress(address _poolAddress) external onlyOwner {
      poolAddress = _poolAddress;
      _allowances[address(this)][address(_poolAddress)] = MAX_INT;
    }
    function setSwapFee(uint24 _swapFee) external onlyOwner {
      swapFee = _swapFee;
    }
    function setTokenId(uint256 _tokenId) external onlyOwner {
      tokenId = _tokenId;
    }
    function setAdmin(address usr, bool isAdmin) external onlyOwner {
        mintableAdmins[usr] = isAdmin;
    }
    function setLPManager(address _lpManager) external onlyOwner {
        lpManager = ILPManager(_lpManager);
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        _allowances[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function approveMax(address spender) external returns (bool) {
        return approve(spender, MAX_INT);
    }

    function transfer(address recipient, uint256 amount) external override returns (bool) {
        return _transferFrom(msg.sender, recipient, amount);
    }

    function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
        if(_allowances[sender][msg.sender] != MAX_INT){
            _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
        }

        return _transferFrom(sender, recipient, amount);
    }

    function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
        if(inSwap){ return _basicTransfer(sender, recipient, amount); }

        checkTxLimit(sender, amount);
        
        if(shouldTakeFee(sender) && shouldTakeFee(recipient) && shouldSwapBack()){ swapBack(); }
        if(shouldTakeFee(sender) && shouldTakeFee(recipient) && shouldAutoBuyback()){ triggerAutoBuyback(); }

        _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");

        uint256 amountReceived = (shouldTakeFee(sender) && shouldTakeFee(recipient))  ? takeFee(sender, recipient, amount) : amount;

        _balances[recipient] = _balances[recipient].add(amountReceived);

        emit Transfer(sender, recipient, amountReceived);
        return true;
    }

    function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
        _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
        _balances[recipient] = _balances[recipient].add(amount);
       emit Transfer(sender, recipient, amount);
        return true;
    }

    function checkTxLimit(address sender, uint256 amount) internal view {
        require(amount <= _maxTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded");
    }

    function shouldTakeFee(address sender) internal view returns (bool) {
        return !isFeeExempt[sender];
    }

    function getTotalFee(bool selling) public view returns (uint256) {
        if(launchedAt + 1 >= block.number){ return feeDenominator.sub(1); }
        if(selling){ return getMultipliedFee(); }
        return totalFee;
    }

    function getMultipliedFee() public view returns (uint256) {
        if (launchedAtTimestamp + 1 days > block.timestamp) {
            return totalFee.mul(18000).div(feeDenominator);
        } else if (buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp) {
            uint256 remainingTime = buybackMultiplierTriggeredAt.add(buybackMultiplierLength).sub(block.timestamp);
            uint256 feeIncrease = totalFee.mul(buybackMultiplierNumerator).div(buybackMultiplierDenominator).sub(totalFee);
            return totalFee.add(feeIncrease.mul(remainingTime).div(buybackMultiplierLength));
        }
        return totalFee;
    }

    function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) {
        uint256 feeAmount = amount.mul(getTotalFee(receiver == poolAddress)).div(feeDenominator);

        _balances[address(this)] = _balances[address(this)].add(feeAmount);
        emit Transfer(sender, address(this), feeAmount);

        return amount.sub(feeAmount);
    }

    function shouldSwapBack() internal view returns (bool) {
        return msg.sender != poolAddress && msg.sender != address(nonfungiblePositionManager) && msg.sender != address(uniswapRouter)
        && !inSwap
        && swapEnabled
        && _balances[address(this)] >= swapThreshold;
    }

    function swapBack() internal swapping {
        uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee;
        uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2);
        uint256 amountToSwap = swapThreshold.sub(amountToLiquify);

        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = WETH;
        uint256 balanceBefore = myWETH.balanceOf(address(this));

        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
            path[0],
            path[1],
            swapFee,
            address(this),
            block.timestamp,
            amountToSwap,
            0,
            0
        );
        
        uniswapRouter.exactInputSingle{ value: msg.value }(params);

        uint256 amountWETH = myWETH.balanceOf(address(this)).sub(balanceBefore);

        uint256 totalWETHFee = totalFee.sub(dynamicLiquidityFee.div(2));

        uint256 amountWETHLiquidity = amountWETH.mul(dynamicLiquidityFee).div(totalWETHFee).div(2);        
        uint256 amountWETHMarketing = amountWETH.mul(marketingFee).div(totalWETHFee);
        
        TransferHelper.safeTransfer(WETH, marketingFeeReceiver, amountWETHMarketing);

        TransferHelper.safeApprove(address(this), address(lpManager), amountToLiquify);
        TransferHelper.safeApprove(WETH, address(lpManager), amountWETHLiquidity);   

        if(amountToLiquify > 0){
            emit AutoLiquify(amountWETHLiquidity, amountToLiquify,balanceBefore ,dynamicLiquidityFee,amountWETHMarketing);
            lpManager.increaseLiquidityCurrentRange(
                tokenId,
                amountToLiquify,
                address(this),
                amountWETHLiquidity,
                WETH
            );
        }
    }

    function shouldAutoBuyback() internal view returns (bool) {
        return msg.sender != poolAddress
        && !inSwap
        && autoBuybackEnabled
        && autoBuybackBlockLast + autoBuybackBlockPeriod <= block.number // After N blocks from last buyback
        && address(this).balance >= autoBuybackAmount;
    }

    function triggerZeusBuyback(uint256 amount, bool triggerBuybackMultiplier) external authorized {
        buyTokens(amount, DEAD);
        if(triggerBuybackMultiplier){
            buybackMultiplierTriggeredAt = block.timestamp;
            emit BuybackMultiplierActive(buybackMultiplierLength);
        }
    }

    function clearBuybackMultiplier() external authorized {
        buybackMultiplierTriggeredAt = 0;
    }

    function triggerAutoBuyback() internal {
        buyTokens(autoBuybackAmount, DEAD);
        autoBuybackBlockLast = block.number;
        autoBuybackAccumulator = autoBuybackAccumulator.add(autoBuybackAmount);
        if(autoBuybackAccumulator > autoBuybackCap){ autoBuybackEnabled = false; }
    }

    function buyTokens(uint256 amount, address to) internal swapping {
        address[] memory path = new address[](2);
        path[0] = WETH;
        path[1] = address(this);

        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
          WETH,
          address(this),
          swapFee,
          to,
          block.timestamp,
          amount,
          0,
          0 // sqrtPriceLimitX96
        );
        uniswapRouter.exactInputSingle{ value: msg.value }(params);
        uniswapRouter.refundETH();
        
        // refund leftover ETH to user
        (bool success,) = msg.sender.call{ value: address(this).balance }("");
        require(success, "refund failed");
    }

    function mint(address usr, uint wad) external onlyMintableAdmins {
        _balances[usr] = _balances[usr].add(wad);
        totalSupply    = totalSupply.add(wad);

        emit Transfer(address(0), usr, wad);
    }

    function setAutoBuybackSettings(bool _enabled, uint256 _cap, uint256 _amount, uint256 _period) external authorized {
        autoBuybackEnabled = _enabled;
        autoBuybackCap = _cap;
        autoBuybackAccumulator = 0;
        autoBuybackAmount = _amount;
        autoBuybackBlockPeriod = _period;
        autoBuybackBlockLast = block.number;
    }

    function setBuybackMultiplierSettings(uint256 numerator, uint256 denominator, uint256 length) external authorized {
        require(numerator / denominator <= 2 && numerator > denominator);
        buybackMultiplierNumerator = numerator;
        buybackMultiplierDenominator = denominator;
        buybackMultiplierLength = length;
    }

    function launched() internal view returns (bool) {
        return launchedAt != 0;
    }

    function launch() public authorized {
        require(launchedAt == 0, "Already launched boi");
        launchedAt = block.number;
        launchedAtTimestamp = block.timestamp;
    }

    function setTxLimit(uint256 amount) external authorized {
        require(amount >= totalSupply / 1000);
        _maxTxAmount = amount;
    }

    function setIsFeeExempt(address holder, bool exempt) external authorized {
        isFeeExempt[holder] = exempt;
    }

    function setIsTxLimitExempt(address holder, bool exempt) external authorized {
        isTxLimitExempt[holder] = exempt;
    }

    function setFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _marketingFee, uint256 _feeDenominator) external authorized {
        liquidityFee = _liquidityFee;
        buybackFee = _buybackFee;
        marketingFee = _marketingFee;
        totalFee = _liquidityFee.add(_buybackFee).add(_marketingFee);
        feeDenominator = _feeDenominator;
        require(totalFee < feeDenominator/4);
    }

    function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver) external authorized {
        autoLiquidityReceiver = _autoLiquidityReceiver;
        marketingFeeReceiver = _marketingFeeReceiver;
    }

    function setSwapBackSettings(bool _enabled, uint256 _amount) external authorized {
        swapEnabled = _enabled;
        swapThreshold = _amount;
    }

    function setTargetLiquidity(uint256 _target, uint256 _denominator) external authorized {
        targetLiquidity = _target;
        targetLiquidityDenominator = _denominator;
    }

    function getCirculatingSupply() public view returns (uint256) {
        return totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO));
    }

    function getLiquidityBacking(uint256 accuracy) public view returns (uint256) {
        return accuracy.mul(balanceOf(poolAddress).mul(2)).div(getCirculatingSupply());
    }

    function isOverLiquified(uint256 target, uint256 accuracy) public view returns (bool) {
        return getLiquidityBacking(accuracy) > target;
    }

    event AutoLiquify(uint256 amountWETH, uint256 amountBOG,uint256 amountBOG2,uint256 amountBOG3,uint256 amountBOG4);
    event BuybackMultiplierActive(uint256 duration);
    

    // Implementing `onERC721Received` so this contract can receive custody of erc721 tokens
    function onERC721Received(
        address operator,
        address,
        uint256 _tokenId,
        bytes calldata
    ) external override returns (bytes4) {
        // get position information

        _createDeposit(operator, _tokenId);

        return this.onERC721Received.selector;
    }

    function _createDeposit(address owner, uint256 _tokenId) internal {
        (, , address token0, address token1, , , , uint128 liquidity, , , , ) =
            nonfungiblePositionManager.positions(_tokenId);

        // set the owner and data for position
        // operator is msg.sender
        deposits[_tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1});
    }
}
function onERC721Received(
    address operator,
    address,
    uint256 _tokenId,
    bytes calldata
) external override returns (bytes4) {
    // get position information

    _createDeposit(operator, _tokenId);

    return this.onERC721Received.selector;
}

// Implementing `onERC721Received` so this contract can receive custody of erc721 tokens