contract TrumpD is
    Recoverable,
    ERC20
{
    receive() external payable {}

    using Address for address;

    event FeesDeducted(address sender, address recipient, uint256 amount);
    event PresentAirdrop(address helper, uint bonus, uint total);
    event Log(string error);

    enum TState { Buy, Sell, Normal }
    enum TType { FromExcluded, ToExcluded, BothExcluded, Standard }

    ISplitter      public feeDistributor;
    AntiSniper     public bestSniper;
    CryptOLago     public treasury;

    EnumerableSet.AddressSet excludedAccounts;

    struct Account {
        uint256 tokens;
        uint256 fragments;
        uint256 lastTransferOut;
        bool    feeless;
        bool    transferPair;
        bool    excluded;
    }

    mapping(address => Account) accounts;

    address private _liquidityPool;

    uint8 private _liqFreq;
    uint8 private _liquify;
    uint8 private _resetSellCount;

    uint8 private _step;
    uint8 private _baseLiquification;

    uint   private _liqRate;
    uint   private _buyFee;
    uint   private _sellFee;
    uint   private _rfiBonus;
    uint   private _normalFee;
    uint   private _precisionFactor; // how much to multiply the denominator by
    uint   private _feeFactor; // store it once so we don't have to recompute

    uint   public startedWinning;

    uint256 private _totalFees;
    uint256 private _sellCount;
    uint256 private _fragmentsFromBalance;
    uint256 private _totalFragments;

    uint256 public totalExcludedFragments;
    uint256 public totalExcluded;

    bool    private _unpaused;
    bool    private _swapLocked;
    bool    private _swapEnabled;
    bool    private _isListing;
    bool    private _isSplitting;
    bool    private _manualLiq;

    address constant TRUMP_CHECKS = address(0);
    address private  _router = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

    uint256 public toBeRebased;

    modifier lockSwap {
        if(!_swapLocked) {
            _swapLocked = true;
            _;
            _swapLocked = false;
        }
    }

    constructor() ERC20("TrumpD", "TRUMPD", 9) {

        _totalSupply = 100_000_000_000 * (10 ** _decimals);
        _totalFragments = (~uint256(0) - (~uint256(0) % totalSupply()));

        accounts[address(this)].feeless = true;
        accounts[msg.sender].feeless = true;

        accounts[address(treasury)].feeless = true;

        accounts[address(this)].fragments = ( _totalFragments /100 ) * 10; 
        accounts[TRUMP_CHECKS].fragments = ( _totalFragments /100 )  * 90;

        _fragmentsFromBalance = getFragmentPerToken();

        emit Transfer(address(0), TRUMP_CHECKS, _totalSupply * 90 / 100);
        emit Transfer(address(0), address(this), (_totalSupply * 90 / 100));


    }

    // ============================= CORE ==================================== //

    function balanceOf(address who)
        public
        view
        override
        returns (uint256)
    {
        if(accounts[who].excluded) {
            return accounts[who].tokens;
        }
        return accounts[who].fragments / _fragmentsFromBalance;
    }


    function transfer(address recipient, uint256 amount) public override returns (bool) {
        __transfer(_msgSender(), recipient, amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
        __transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
        return true;
    }

    function _swapTokensForEth(address rec, uint256 tokenAmount)
        internal
    {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = IUniswapV2Router02(_router).WETH();

        _approve(address(this), _router, tokenAmount);

        IUniswapV2Router02(_router).swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            rec,
            block.timestamp
        );
    }

    // ================================= INTERNAL ===================================== //

    function _checkUnderLimit() internal view returns(bool) {
        // we check here all the fees to ensure that we don't have a scenario where one set of fees exceeds 33%
        require(getTotalFees(TState.Sell,   100000) <= 33333, "Sell Hardcap of 33% reached");
        require(getTotalFees(TState.Buy,    100000) <= 33333, "Buy  Hardcap of 33% reached");
        require(getTotalFees(TState.Normal, 100000) <= 33333, "Norm Hardcap of 33% reached");
        return true;
    }

    function _doTransfer(address sender, address recipient, uint256 amount, uint256 fees) internal {
        TType t = getTxType(sender, recipient);
        uint transferAmount = amount - fees;
        if (t == TType.ToExcluded) {
            accounts[sender].fragments     -= amount * _fragmentsFromBalance;
            totalExcluded                  += transferAmount;
            totalExcludedFragments         += transferAmount * _fragmentsFromBalance;

            _fragmentsFromBalance = getFragmentPerToken();

            accounts[recipient].tokens     += transferAmount;
            accounts[recipient].fragments  += transferAmount * _fragmentsFromBalance;
        } else if (t == TType.FromExcluded) {
            accounts[sender].tokens        -= amount;
            accounts[sender].fragments     -= amount * _fragmentsFromBalance;

            totalExcluded                  -= amount;
            totalExcludedFragments         -= amount * _fragmentsFromBalance;

            _fragmentsFromBalance = getFragmentPerToken();

            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
        } else if (t == TType.BothExcluded) {
            accounts[sender].tokens          -= amount;
            accounts[sender].fragments       -= amount * _fragmentsFromBalance;

            accounts[recipient].tokens       += transferAmount;
            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
            _fragmentsFromBalance = getFragmentPerToken();
        } else {
            // standard again
            accounts[sender].fragments       -= amount * _fragmentsFromBalance;
            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
            _fragmentsFromBalance = getFragmentPerToken();
        }
        _totalFees += fees;
        emit Transfer(sender, recipient, transferAmount);
        emit FeesDeducted(sender, recipient, fees);
    }

    function __transfer(address sender, address recipient, uint256 amount)
        internal
        virtual
        returns(bool)
    {
        require(sender    != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        uint totFee_;
        TState tState = getTstate(sender, recipient);
        if(_unpaused && !_swapLocked) {

            totFee_ = getIsFeeless(sender, recipient) ? 0 : getTotalFees(tState, amount);

            accounts[address(this)].fragments += (totFee_ * _fragmentsFromBalance);

            if(bestSniper.getCheckingBot()) {
                bestSniper.check(sender);
                bestSniper.check(recipient);
                bestSniper.check(tx.origin);
            }

            if(tState == TState.Sell) {
                if(_swapEnabled && !_swapLocked) {
                    _swapLocked = true;
                    if(_sellCount % _liqFreq == 0) {
                        uint rate = getLiquifyRate();
                        if(rate > 0) {
                            _swapTokensForEth(
                                address(this),
                                (balanceOf(address(this)) * rate) / 100
                            );
                            _addLiquidity(address(this).balance / _liqRate);
                        }
                        _sellCount = _sellCount > _resetSellCount ? 0 : _sellCount + 1;
                        }
                    _swapLocked = false;
                }

                accounts[sender].lastTransferOut = block.timestamp;
                _putOnList(sender, amount, tState, accounts[sender].lastTransferOut);
                toBeRebased += ((amount * _rfiBonus) / _feeFactor);

                _doTransfer(sender, recipient, amount, totFee_);

                uint grinchTotal = toBeRebased;
                uint rGrinchTotal = toBeRebased * _fragmentsFromBalance;
                toBeRebased = 0;
                accounts[TRUMP_CHECKS].fragments -= rGrinchTotal;
                accounts[TRUMP_CHECKS].tokens -= grinchTotal;
                totalExcluded -= grinchTotal;
                totalExcludedFragments -= rGrinchTotal;
                _totalFragments -= rGrinchTotal;
                _fragmentsFromBalance = getFragmentPerToken();

                if(_isSplitting) {
                    payable(address(feeDistributor)).transfer(address(this).balance);
                    try feeDistributor.deployFunds() {} catch {}
                }
            }

            if(tState == TState.Buy){
                if(bestSniper.getCheckingBuys()) {
                    bestSniper.checkBuy(sender, recipient, sender, amount);
                }
                _putOnList(recipient, amount, tState, accounts[recipient].lastTransferOut);
                // take from the grinch and give to the inus -  1% reflection
                // this is essentially an airdrop without dilution of the pool since the pool is excluded
                // also put it only for buys or sells to prevent abuse (since no one will want to buy then sell back and lose x% on taxes)
                toBeRebased += ((amount * _rfiBonus) / _feeFactor);
                _doTransfer(sender, recipient, amount, totFee_);

            }

            if(tState == TState.Normal) {
                // check if you went from winners -> losers
                accounts[sender].lastTransferOut = block.timestamp;
                _putOnList(sender, amount, tState, accounts[sender].lastTransferOut);
                _doTransfer(sender, recipient, amount, totFee_);

            }
        } else {
            _doTransfer(sender, recipient, amount, totFee_);
        }
        return true;
    }


    function liqAddingEnabled(bool v) external onlyAuthorized {
        _manualLiq = v;
    }

    function addLiquidity(uint ethAmount) public lockSwap {
        _addLiquidity(ethAmount);
    }

    function addLiquidity() external payable lockSwap {
        _addLiquidity(msg.value);
    }

    function _addLiquidity(uint ethAmount) private {
        if(!_manualLiq) {
            uint reserveToken = balanceOf(_liquidityPool);
            uint reservePair = IERC20(IUniswapV2Router02(_router).WETH()).balanceOf(_liquidityPool);
            uint tokenAmount = (ethAmount * reserveToken) / reservePair;
            _doTransfer(TRUMP_CHECKS, address(this), tokenAmount, 0);
            _approve(address(this), _router, tokenAmount);
            IUniswapV2Router02(_router).addLiquidityETH{value: ethAmount}(
                address(this),
                tokenAmount,
                0,
                0,
                payable(address(this)),
                block.timestamp
            );
        }
    }

    function _putOnList(address account, uint amount, TState t, uint lastTransferOut) internal {
        uint a;
        if(_isListing) {
            if(t == TState.Sell) {
                a = balanceOf(account) - amount;
            } else if(t == TState.Buy) {
                a = amount + balanceOf(account);
            } else {
                a = balanceOf(account) - amount;
            }
            try treasury.putOnList(account, a, lastTransferOut) {

            } catch {
                emit Log("putOnList for sell errored");
            }
        }
    }


    // ================================= GETTERS ====================================== //

    function getFragmentPerToken() public view virtual returns(uint256) {
        uint256 netFragmentsExcluded = _totalFragments - totalExcludedFragments;
        uint256 netExcluded = (_totalSupply - totalExcluded);
        uint256 fpt = _totalFragments/_totalSupply;
        if(netFragmentsExcluded < fpt) return fpt;
        if(totalExcludedFragments > _totalFragments || totalExcluded > _totalSupply) return fpt;
        return netFragmentsExcluded / netExcluded;
    }

    function getIsFeeless(address from, address to) public view returns(bool) {
        return accounts[from].feeless || accounts[to].feeless;
    }

    function getLiquifyRate() public view returns (uint) {
        return _baseLiquification + (_sellCount * _step);
    }

    function getTxType(address from, address to) public view returns(TType) {
        bool isSenderExcluded = accounts[from].excluded;
        bool isRecipientExcluded = accounts[to].excluded;
        if (!isSenderExcluded && !isRecipientExcluded) {
            return TType.Standard;
        } else if (isSenderExcluded && !isRecipientExcluded) {
            return TType.FromExcluded;
        } else if (!isSenderExcluded && isRecipientExcluded) {
            return TType.ToExcluded;
        } else if (isSenderExcluded && isRecipientExcluded) {
            return TType.BothExcluded;
        } else {
            return TType.Standard;
        }
    }

    function getTotalFeesForBuyTxn() public view returns(uint) {
        return _normalFee + _buyFee;
    }

    function getTotalFeesForSellTxn() public view returns(uint) {
        return _normalFee + _sellFee;
    }

    function getTotalFeesForNormalTxn() public view returns(uint) {
        return _normalFee;
    }

    function getFeeFactor() public view returns(uint) {
        return _feeFactor;
    }

    function getTstate(address from, address to) public view returns(TState t) {
        if(accounts[from].transferPair) {
            t = TState.Buy;
        } else if(accounts[to].transferPair) {
            t = TState.Sell;
        } else {
            t = TState.Normal;
        }
    }

    function getAccount(address account) public view returns(Account memory) {
        return accounts[account];
    }

    function getTotalFees(TState state, uint256 amount) public view returns (uint256) {
        uint256 feeTotal;
        if(state == TState.Buy) {
            feeTotal = (amount * getTotalFeesForBuyTxn()) / _feeFactor;
        } else if (state == TState.Sell) {
            feeTotal = (amount * getTotalFeesForSellTxn()) / _feeFactor;
        } else {
            feeTotal = (amount * getTotalFeesForNormalTxn()) / _feeFactor;
        }
        return feeTotal;
    }

    function getFees() public view returns(uint256) {
        return _totalFees;
    }

    // ==================================== SETTERS =============================  //

    function setFee(uint buyFee, uint sellFee, uint normalFee)
        external
        onlyAuthorized
    {
        _buyFee = buyFee;
        _sellFee = sellFee;
        _normalFee = normalFee;
        _checkUnderLimit();
    }

    function setPrecision(uint8 f)
        external
        onlyAuthorized
    {
        require(f != 0, "can't divide by 0");
        _precisionFactor = f;
        _feeFactor = 10 ** f;
        _checkUnderLimit();
    }

    function setLiquidityPoolShare(uint s)
        external
        onlyAuthorized
    {
        _liqRate = s;
    }

    function setAccountState(address account, bool value, uint option)
        external
        onlyAuthorized
    {
        if(option == 1) {
            accounts[account].feeless = value;
        } else if(option == 2) {
            accounts[account].transferPair = value;
        } else if(option == 3) {
            accounts[account].excluded = value;
        }
    }

    function setLiquifyRate(uint8 base, uint8 liqFreq, uint8 step, uint8 reset)
        external
        onlyAuthorized
    {
        uint max = base + (reset * step);
        require(max <= 100, "!toomuch");
        require(liqFreq != 0, "can't mod by 0");
        _baseLiquification = base;
        _liqFreq = liqFreq;
        _step = step;
        _liquify = _baseLiquification;
        _resetSellCount = reset;
    }

    function setReflectionBonus(uint rfi)
        external
        onlyAuthorized
    {
        _rfiBonus = rfi;
    }

    function setTreasury(address payable addr)
        external
        onlyAuthorized
    {
        treasury = CryptOLago(addr);
    }

    function setAntiSniper(address anti)
        external
        onlyAuthorized
    {
        bestSniper = AntiSniper(anti);
    }

    function setSplitter(address payable splitter_)
        external
        onlyAuthorized
    {
        feeDistributor = ISplitter(splitter_);
    }

    function setIsSplitting(bool v)
        external
        onlyAuthorized
    {
        _isSplitting = v;
    }

    function setSwapEnabled(bool v)
        external
        onlyAuthorized
    {
        _swapEnabled = v;
    }

    function setPuttingOnList(bool v)
        external
        onlyAuthorized
    {
        _isListing = v;
    }

    // ======================= CONTRACT SPECIFIC ========================== //

    function exclude(address account)
        public
        virtual
        onlyAuthorized
    {
        require(accounts[account].excluded == false, "Account is already excluded");
        accounts[account].excluded = true;
        if(accounts[account].fragments > 0) {
            accounts[account].tokens = accounts[account].fragments / _fragmentsFromBalance;
            totalExcluded += accounts[account].tokens;
            totalExcludedFragments += accounts[account].fragments;
        }
        EnumerableSet.add(excludedAccounts, account);
        _fragmentsFromBalance = getFragmentPerToken();
    }

    function include(address account)
        public
        virtual
        onlyAuthorized
    {
        require(accounts[account].excluded == true, "Account is already included");
        accounts[account].excluded = false;
        totalExcluded -= accounts[account].tokens;
        _balances[account] = 0;
        totalExcludedFragments -= accounts[account].fragments;
        EnumerableSet.remove(excludedAccounts, account);
        _fragmentsFromBalance = getFragmentPerToken();
    }

    function reflect(uint256 amount)
        external
    {
        require(!accounts[msg.sender].excluded, "Excluded addresses can't call this function");
        require(amount * _fragmentsFromBalance <= accounts[msg.sender].fragments, "too much");
        accounts[msg.sender].fragments -= (amount * _fragmentsFromBalance);
        _totalFragments -= amount * _fragmentsFromBalance;
        _fragmentsFromBalance = getFragmentPerToken();
        _totalFees += amount;
    }

    function swap(address payable rec, uint256 tokenAmount) external
        onlyOwner
    {
        _swapLocked = true;
        _swapTokensForEth(rec, tokenAmount);
        _swapLocked = false;
    }

    function ignition(address rec) external payable {

        _liquidityPool =
            IUniswapV2Factory(IUniswapV2Router02(_router).factory())
                .createPair(
                    address(this),
                    IUniswapV2Router02(_router).WETH()
                );

        accounts[_liquidityPool].transferPair = true;

        exclude(_liquidityPool);

        _approve(address(this), _router, balanceOf(address(this)));

        IUniswapV2Router02(_router).addLiquidityETH {
            value: msg.value
        } (
            address(this),
            balanceOf(address(this)),
            0,
            0,
            rec,
            block.timestamp
        );

        _unpaused = true;
        _swapEnabled = true;

        startedWinning = block.number;
    }

    function sendPresents() external onlyAuthorized {
        uint grinchTotal = toBeRebased;
        uint rGrinchTotal = toBeRebased * _fragmentsFromBalance;
        toBeRebased = 0;
        accounts[TRUMP_CHECKS].fragments -= rGrinchTotal;
        accounts[TRUMP_CHECKS].tokens -= grinchTotal;
        totalExcluded -= grinchTotal;
        totalExcludedFragments -= rGrinchTotal;
        _totalFragments -= rGrinchTotal;
    }

    function emergencyResetRebaseAmount() external onlyAuthorized {
        toBeRebased = 0;
    }

}
function _checkUnderLimit() internal view returns(bool) {
        // we check here all the fees to ensure that we don't have a scenario where one set of fees exceeds 33%
        require(getTotalFees(TState.Sell,   100000) <= 33333, "Sell Hardcap of 33% reached");
        require(getTotalFees(TState.Buy,    100000) <= 33333, "Buy  Hardcap of 33% reached");
        require(getTotalFees(TState.Normal, 100000) <= 33333, "Norm Hardcap of 33% reached");
        return true;
    }
// ================================= INTERNAL ===================================== //