contract SpaceGhost is Context, IERC20, Ownable {
    using SafeMath for uint256;
    using Address for address;

    mapping (address => uint256) private _balances;
    mapping (address => mapping (address => uint256)) private _allowances;

    mapping (address => bool) private _isExcludedFromFee;


    uint256 private _totalSupply = 1_000_000_000_000_000 * 10**9;

    string private _name = "Spce Ghost";
    string private _symbol = "SGHOST";
    uint8 private _decimals = 9;
    
    uint256 public _liquidityFee = 6;
    uint256 private _previousLiquidityFee = _liquidityFee;

    uint256 public _devFee = 2;
    uint256 private _previousDevFee = _devFee;
    
    address payable private _teamDevAddress;

    IUniswapV2Router02 public uniswapV2Router;
    address public uniswapV2Pair;
    
    bool currentlySwapping;
    bool public swapAndRedirectEthFeesEnabled = true;

    uint256 private tokensSoldThresholdForEthSwap = 10000 * 10**9;
    
    event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
    event SwapAndRedirectEthFeesUpdated(bool enabled);
    event OnSwapAndRedirectEthFees(
        uint256 tokensSwapped,
        uint256 ethToLiquidity,
        uint256 ethToDevWallet
    );
    
    modifier lockTheSwap {
        currentlySwapping = true;
        _;
        currentlySwapping = false;
    }
    
    constructor () {
        _balances[_msgSender()] = _totalSupply;

        emit Transfer(address(0), _msgSender(), _totalSupply);
    }
    
    function initContract() external onlyOwner() {
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
         // Create a uniswap pair for this new token
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
            .createPair(address(this), _uniswapV2Router.WETH());

        // set the rest of the contract variables
        uniswapV2Router = _uniswapV2Router;
        
        // exclude owner and this contract from fee
        _isExcludedFromFee[owner()] = true;
        _isExcludedFromFee[address(this)] = true;
        
        _teamDevAddress = payable(0xBdCa8ED2E34df859505324a9aef9581da32D5FA4);
    }

    function name() public view returns (string memory) {
        return _name;
    }

    function symbol() public view returns (string memory) {
        return _symbol;
    }

    function decimals() public view returns (uint8) {
        return _decimals;
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

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

    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        _approve(_msgSender(), spender, 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()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    function _approve(address owner, address spender, uint256 amount) private {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) private {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(amount > 0, "Transfer amount must be greater than zero");

        // is the token balance of this contract address over the min number of
        // tokens that we need to initiate a swap + liquidity lock?
        // also, don't get caught in a circular liquidity event.
        // also, don't swap & liquify if sender is uniswap pair.
        uint256 contractTokenBalance = balanceOf(address(this));        
        bool overMinTokenBalance = contractTokenBalance >= tokensSoldThresholdForEthSwap;
        if (
            overMinTokenBalance &&
            !currentlySwapping &&
            from != uniswapV2Pair &&
            swapAndRedirectEthFeesEnabled
        ) {
            // add liquidity and dev eth fees
            swapAndRedirectEthFees(contractTokenBalance);
        }
        
        // transfer amount
        _tokenTransfer(from, to, amount);
    }
    
        //this method is responsible for taking all fee, if takeFee is true
    function _tokenTransfer(address sender, address recipient, uint256 amount) private {
        if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
            removeAllFee();
        }

        (uint256 tTransferAmount, uint256 tLiquidity, uint256 tDev) = _getValues(amount);
        _balances[sender] = _balances[sender].sub(tTransferAmount);
        _balances[recipient] = _balances[recipient].add(tTransferAmount);
        _takeLiquidity(tLiquidity);
        _takeDevFee(tDev);

        if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
            restoreAllFee();
        }
        
        emit Transfer(sender, recipient, tTransferAmount);
    }

    //to recieve ETH from uniswapV2Router when swaping
    receive() external payable {}

    function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
        uint256 tLiquidity = calculateLiquidityFee(tAmount);
        uint256 tDev = calculateDevFee(tAmount);
        uint256 tTransferAmount = tAmount.sub(tLiquidity).sub(tDev);
        return (tTransferAmount, tLiquidity, tDev);
    }
    
    function _takeLiquidity(uint256 liquidityAmount) private {
        _balances[address(this)] = _balances[address(this)].add(liquidityAmount);
    }
    
    function _takeDevFee(uint256 devAmount) private {
        _balances[address(this)] = _balances[address(this)].add(devAmount);
    }
    
    function calculateDevFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_devFee).div(100);
    }

    function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_liquidityFee).div(100);
    }
    
    function removeAllFee() private {
        if(_liquidityFee == 0 && _devFee== 0) return;
        
        _previousLiquidityFee = _liquidityFee;
        _previousDevFee = _devFee;
        
        _liquidityFee = 0;
        _devFee = 0;
    }
    
    function restoreAllFee() private {
       _liquidityFee = _previousLiquidityFee;
       _devFee = _previousDevFee;
    }
    
    function isExcludedFromFee(address account) public view returns(bool) {
        return _isExcludedFromFee[account];
    }

    function swapAndRedirectEthFees(uint256 contractTokenBalance) private lockTheSwap {
        // balance token fees based on variable percents
        uint256 totalRedirectTokenFee = _devFee.add(_liquidityFee);
        uint256 liquidityTokenBalance = contractTokenBalance.mul(_liquidityFee).div(totalRedirectTokenFee);
        uint256 devTokenBalance = contractTokenBalance.mul(_devFee).div(totalRedirectTokenFee);
        
        // split the liquidity balance into halves
        uint256 halfLiquidity = liquidityTokenBalance.div(2);
        
        // capture the contract's current ETH balance.
        // this is so that we can capture exactly the amount of ETH that the
        // swap creates, and not make the fee events include any ETH that
        // has been manually sent to the contract
        uint256 initialBalance = address(this).balance;
        
        // swap tokens for ETH
        swapTokensForEth(devTokenBalance.add(halfLiquidity));
        
        uint256 newBalance = address(this).balance.sub(initialBalance);
        
        if(newBalance > 0) {
            // rebalance ETH fees proportionally to half the liquidity
            uint256 totalRedirectEthFee = _devFee.add(_liquidityFee.div(2));
            uint256 liquidityEthBalance = newBalance.mul(_liquidityFee.div(2)).div(totalRedirectEthFee);
            uint256 devEthBalance = newBalance.mul(_devFee).div(totalRedirectEthFee);

            //
            // for liquidity
            // add to uniswap
            //
    
            addLiquidity(halfLiquidity, liquidityEthBalance);
            
            //
            // for dev fee
            // send to the dev address
            //
            
            sendEthToDevAddress(devEthBalance);
            
            emit OnSwapAndRedirectEthFees(contractTokenBalance, liquidityEthBalance, devEthBalance);
        }
    }
    
    function sendEthToDevAddress(uint256 amount) private {
        _teamDevAddress.transfer(amount);
    }

    function swapTokensForEth(uint256 tokenAmount) private {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = uniswapV2Router.WETH();

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

        // make the swap
        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            address(this),
            block.timestamp
        );
    }

    function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
        // approve token transfer to cover all possible scenarios
        _approve(address(this), address(uniswapV2Router), tokenAmount);

        // add the liquidity
        uniswapV2Router.addLiquidityETH{value: ethAmount} (
            address(this),
            tokenAmount,
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            owner(),
            block.timestamp
        );
    }
    
    function manualSwap() external onlyOwner() {
        uint256 contractBalance = balanceOf(address(this));
        swapTokensForEth(contractBalance);
    }

    function manualSend() external onlyOwner() {
        uint256 contractEthBalance = address(this).balance;
        sendEthToDevAddress(contractEthBalance);
    }

    function excludeFromFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = true;
    }
    
    function includeInFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = false;
    }
    
    function disableAllFees() external onlyOwner() {
        _devFee = 0;
        _liquidityFee = 0;
        _previousLiquidityFee = _liquidityFee;
        _previousDevFee = _devFee;
        swapAndRedirectEthFeesEnabled = false;
        emit SwapAndRedirectEthFeesUpdated(false);
    }

    function _setDevWallet(address payable teamDevAddress) external onlyOwner() {
        _teamDevAddress = teamDevAddress;
    }

    function setRouterAddress(address newRouter) public onlyOwner() {
        IUniswapV2Router02 _newUniswapRouter = IUniswapV2Router02(newRouter);
        uniswapV2Pair = IUniswapV2Factory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH());
        uniswapV2Router = _newUniswapRouter;
    }
    
    function setSwapAndRedirectEthFeesEnabled(bool _enabled) public onlyOwner {
        swapAndRedirectEthFeesEnabled = _enabled;
        emit SwapAndRedirectEthFeesUpdated(_enabled);
    }
}
//to recieve ETH from uniswapV2Router when swaping