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

    mapping (address => uint256) private _rOwned;
    mapping (address => uint256) private _tOwned;
    mapping (address => mapping (address => uint256)) private _allowances;
    mapping (address => uint256) public _firstBuyTime;
    mapping (address => bool) private _isExcludedFromFee;

    address payable public marketing;
    address payable public charity;
    address payable private _burnPool = 0x0000000000000000000000000000000000000000;

    uint256 private constant MAX = ~uint256(0);
    uint256 private _tTotal = 100 * 10**15 * 10**9;
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;

    string private _name = "Hero Inu";
    string private _symbol = "HEROS";
    uint8 private _decimals = 9;

    uint256 public _taxBuyFee = 2;
    uint256 public _taxSellFee = 2;
    uint256 public _taxTransferFee = 1;

    uint256 private _operationsFee = 0; //adjusted on the go
    uint256 private _liquidityFee = 0; //adjusted on the go
    uint256 private _taxFee = 0; //adjusted on the go
    uint256 private _burnFee = 0; //adjusted on the go

    uint256 public _marketingBuyFee = 3;
    uint256 public _marketingSellFee = 3;
    uint256 public _marketingTransferFee = 1;

    uint256 public _charityBuyFee = 1;
    uint256 public _charitySellFee = 1;
    uint256 public _charityTransferFee = 1;

    uint256 public _liquidityBuyFee = 2;
    uint256 public _liquiditySellFee = 2;
    uint256 public _liquidityTransferFee = 1;

    uint256 public _burnBuyFee = 2;
    uint256 public _burnSellFee = 2;
    uint256 public _burnTransferFee = 1;

    uint256 public _prev_liquiditySellFee = 0;
    uint256 public _prev_burnSellFee = 0;
    uint256 public _prev_marketingSellFee = 0;
    uint256 public _prev_charitySellFee = 0;
    uint256 public _prev_taxSellFee = 0;

    //These fees are accumulated and adjusted on a per-transfer basis up until swapAndLiquify is called, during which the accumulated funds get distributed as intended
    uint256 public _pendingCharityFees = 0;
    uint256 public _pendingLiquidityFees = 0;

    IUniswapV2Router02 public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;

    bool inSwapAndLiquify;
    bool public swapAndLiquifyEnabled = true;

    uint256 public _maxWalletHolding = 3 * 10**15 * 10**9;
    uint256 private numTokensSellToAddToLiquidity = 200 * 10**12 * 10**9;

    event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
    event SwapAndLiquifyEnabledUpdated(bool enabled);
    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiquidity
    );

    modifier lockTheSwap {
        inSwapAndLiquify = true;
        _;
        inSwapAndLiquify = false;
    }

    constructor (address payable _marketing, address payable _charity) public {
      marketing = _marketing;
      charity = _charity;
      _rOwned[_msgSender()] = _rTotal;
      IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
      uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
      uniswapV2Router = _uniswapV2Router;
      _isExcludedFromFee[owner()] = true;
      _isExcludedFromFee[address(this)] = true;
      emit Transfer(address(0), _msgSender(), _tTotal);
    }

    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 _tTotal;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return tokenFromReflection(_rOwned[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 totalFees() public view returns (uint256) {
        return _tFeeTotal;
    }

    function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
        require(tAmount <= _tTotal, "Amount must be less than supply");
        if (!deductTransferFee) {
            (uint256 rAmount,,,,,,) = _getValues(tAmount);
            return rAmount;
        } else {
            (,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
            return rTransferAmount;
        }
    }

    function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
        require(rAmount <= _rTotal, "Amount must be less than total reflections");
        uint256 currentRate =  _getRate();
        return rAmount.div(currentRate);
    }

    //this can be called externally by deployer to immediately process accumulated fees accordingly (distribute to treasury & liquidity)
    function manualSwapAndLiquify() public onlyOwner() {
        uint256 contractTokenBalance = balanceOf(address(this));
        swapAndLiquify(contractTokenBalance);
    }

    function excludeFromFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = true;
    }

    function includeInFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = false;
    }

    function setTax(uint256 _taxType, uint _taxSize) external onlyOwner() {
      if (_taxType == 1) {
        _taxSellFee = _taxSize;
      }
      else if (_taxType == 2) {
        _taxBuyFee = _taxSize;
      }
      else if (_taxType == 3) {
        _taxTransferFee = _taxSize;
      }
      else if (_taxType == 4) {
        _marketingBuyFee = _taxSize;
      }
      else if (_taxType == 5) {
        _marketingSellFee = _taxSize;
      }
      else if (_taxType == 6) {
        _marketingTransferFee = _taxSize;
      }
      else if (_taxType == 7) {
        _burnBuyFee = _taxSize;
      }
      else if (_taxType == 8) {
        _burnSellFee = _taxSize;
      }
      else if (_taxType == 9) {
        _burnTransferFee = _taxSize;
      }
      else if (_taxType == 10) {
        _charityBuyFee = _taxSize;
      }
      else if (_taxType == 11) {
        _charitySellFee = _taxSize;
      }
      else if (_taxType == 12) {
        _charityTransferFee = _taxSize;
      }
      else if (_taxType == 13) {
        _liquidityBuyFee = _taxSize;
      }
      else if (_taxType == 14) {
        _liquiditySellFee = _taxSize;
      }
      else if (_taxType == 15) {
        _liquidityTransferFee = _taxSize;
      }
    }

    function setMaxWalletHoldingPercent(uint256 maxHoldingPercent) external onlyOwner() {
        _maxWalletHolding = _tTotal.mul(maxHoldingPercent).div(
            10**2
        );
    }

    function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
        swapAndLiquifyEnabled = _enabled;
        emit SwapAndLiquifyEnabledUpdated(_enabled);
    }

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

    function _reflectFee(uint256 rFee, uint256 tFee) private {
        _rTotal = _rTotal.sub(rFee);
        _tFeeTotal = _tFeeTotal.add(tFee);
    }

    function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
        uint256[4] memory tValues = _getTValuesArray(tAmount);
        uint256[3] memory rValues = _getRValuesArray(tAmount, tValues[1], tValues[2], tValues[3]);
        return (rValues[0], rValues[1], rValues[2], tValues[0], tValues[1], tValues[2], tValues[3]);
    }

    function _getTValuesArray(uint256 tAmount) private view returns (uint256[4] memory val) {
        uint256 tFee = calculateTaxFee(tAmount);
        uint256 tLiquidity = calculateLiquidityFee(tAmount);
        uint256 tOperations = calculateOperationsFee(tAmount);
        uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tOperations);
        return [tTransferAmount, tFee, tLiquidity, tOperations];
    }

    function _getRValuesArray(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tOperations) private view returns (uint256[3] memory val) {
        uint256 currentRate = _getRate();
        uint256 rAmount = tAmount.mul(currentRate);
        uint256 rFee = tFee.mul(currentRate);
        uint256 rTransferAmount = rAmount.sub(rFee).sub(tLiquidity.mul(currentRate)).sub(tOperations.mul(currentRate));
        return [rAmount, rTransferAmount, rFee];
    }

    function _getRate() private view returns(uint256) {
        (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
        return rSupply.div(tSupply);
    }

    function _getCurrentSupply() private view returns(uint256, uint256) {
        uint256 rSupply = _rTotal;
        uint256 tSupply = _tTotal;
        if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
        return (rSupply, tSupply);
    }

    function _takeLiquidity(uint256 tLiquidity) private {
        uint256 currentRate =  _getRate();
        uint256 rLiquidity = tLiquidity.mul(currentRate);
        _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
        _pendingLiquidityFees = _pendingLiquidityFees.add(tLiquidity);
    }

    function _takeOperations(uint256 tOperations, uint8 transferType) private {
        uint256 currentRate =  _getRate();
        uint256 tBurn = 0;
        if (_operationsFee > 0) {
          tBurn = _burnFee.mul(tOperations).div(_operationsFee);
          emit Transfer(address(this), address(0), tBurn);
        }
        uint256 rOperations = tOperations.sub(tBurn).mul(currentRate);
        _rOwned[address(this)] = _rOwned[address(this)].add(rOperations);
        _rOwned[_burnPool] = _rOwned[_burnPool].add(tBurn.mul(currentRate));

        if (_operationsFee > 0) {
          uint256 _deltaCharityFees = 0;

          if (transferType == 1) {
            _deltaCharityFees = tOperations.mul(_charityBuyFee).div(_operationsFee);
          }
          else if (transferType == 2) {
            _deltaCharityFees = tOperations.mul(_charitySellFee).div(_operationsFee);
          }
          else if (transferType == 0) {
            _deltaCharityFees = tOperations.mul(_charityTransferFee).div(_operationsFee);
          }

          if (_deltaCharityFees > 0) _pendingCharityFees = _pendingCharityFees.add(_deltaCharityFees);
        }

    }

    function calculateTaxFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_taxFee).div(
            10**2
        );
    }

    function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_liquidityFee).div(
            10**2
        );
    }

    function calculateOperationsFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_operationsFee).div(
            10**2
        );
    }

    function removeAllFee() private {
        _taxFee = 0;
        _liquidityFee = 0;
        _operationsFee = 0;
        _burnFee = 0;

        _liquiditySellFee = _prev_liquiditySellFee;
        _marketingSellFee = _prev_marketingSellFee;
        _burnSellFee = _prev_burnSellFee;
        _taxSellFee = _prev_taxSellFee;
        _charitySellFee = _prev_charitySellFee;
    }

    function saveAllFee() private {
        _prev_liquiditySellFee = _liquiditySellFee;
        _prev_marketingSellFee = _marketingSellFee;
        _prev_burnSellFee = _burnSellFee;
        _prev_taxSellFee = _taxSellFee;
        _prev_charitySellFee = _charitySellFee;
    }

    function isExcludedFromFee(address account) public view returns(bool) {
        return _isExcludedFromFee[account];
    }

    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(to != address(0), "ERC20: transfer to the zero address");
        require(amount > 0, "Transfer amount must be greater than zero");
        saveAllFee();
        uint256 contractTokenBalance = balanceOf(address(this));

        bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
        if (
            overMinTokenBalance &&
            !inSwapAndLiquify &&
            from != uniswapV2Pair &&
            swapAndLiquifyEnabled
        ) {
            swapAndLiquify(contractTokenBalance);
        }

        //indicates if fee should be deducted from transfer
        bool takeFee = true;

        //if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
            takeFee = false;
        }

        //depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are imposed
        uint8 transferType = 0;
        bool isTransferBuy = from == uniswapV2Pair;
        bool isTransferSell = to == uniswapV2Pair;

        if (!isTransferBuy && !isTransferSell) {
          _operationsFee = _marketingTransferFee.add(_charityTransferFee).add(_burnTransferFee);
          _liquidityFee = _liquidityTransferFee;
          _taxFee = _taxTransferFee;
          _burnFee = _burnTransferFee;
        }
        else if (isTransferBuy) {
          _operationsFee = _marketingBuyFee.add(_charityBuyFee).add(_burnBuyFee);
          _liquidityFee = _liquidityBuyFee;
          _taxFee = _taxBuyFee;
          _burnFee = _burnBuyFee;
          transferType = 1;
          if (_firstBuyTime[to] == 0) _firstBuyTime[to] = block.timestamp;
        }
        else if (isTransferSell) {
          _operationsFee = _marketingSellFee.add(_charitySellFee).add(_burnSellFee);
          _liquidityFee = _liquiditySellFee;
          _taxFee = _taxSellFee;
          _burnFee = _burnSellFee;
          transferType = 2;
          if (_firstBuyTime[from] != 0 && (_firstBuyTime[from] + (24 hours) > block.timestamp) ) {
            //doubling sell tax when user is flipping within 24 hrs
            _marketingSellFee = _marketingSellFee.mul(2);
            _liquiditySellFee = _liquiditySellFee.mul(2);
            _burnSellFee = _burnSellFee.mul(2);
            _taxSellFee = _taxSellFee.mul(2);
            _charitySellFee = _charitySellFee.mul(2);
            _operationsFee = _operationsFee.mul(2);
            _liquidityFee = _liquidityFee.mul(2);
            _taxFee = _taxFee.mul(2);
            _burnFee = _burnFee.mul(2);
          }
        }

        //transfer amount, it will take tax, liquidity & treasury fees
        _tokenTransfer(from,to,amount,takeFee,transferType);
        removeAllFee();
    }

    function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
        uint256 liquidityPart = 0;
        if (_pendingLiquidityFees < contractTokenBalance) liquidityPart = _pendingLiquidityFees;
        uint256 distributionPart = contractTokenBalance.sub(liquidityPart);
        uint256 liquidityHalfPart = liquidityPart.div(2);
        uint256 liquidityHalfTokenPart = liquidityPart.sub(liquidityHalfPart);

        //now swapping half of the liquidity part + all of the distribution part into ETH
        uint256 totalETHSwap = liquidityHalfPart.add(distributionPart);

        uint256 initialBalance = address(this).balance;

        // swap tokens for ETH
        swapTokensForEth(totalETHSwap);

        uint256 newBalance = address(this).balance.sub(initialBalance);
        uint256 liquidityBalance = liquidityHalfPart.mul(newBalance).div(totalETHSwap);

        // add liquidity to uniswap
        if (liquidityHalfTokenPart > 0 && liquidityBalance > 0) addLiquidity(liquidityHalfTokenPart, liquidityBalance);
        emit SwapAndLiquify(liquidityHalfPart, liquidityBalance, liquidityHalfPart);

        newBalance = address(this).balance;
        uint256 charityETHPart = newBalance.mul(_pendingCharityFees).div(distributionPart);
        uint256 marketingETHPart = newBalance.sub(charityETHPart);
        payDistribution(marketingETHPart, charityETHPart);
        _pendingLiquidityFees = 0;
        _pendingCharityFees = 0;
    }

    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
            address(this),
            block.timestamp
        );
    }

    function payDistribution(uint256 marketingETHPart, uint256 charityETHPart) private {
      marketing.sendValue(marketingETHPart);
      charity.sendValue(charityETHPart);
    }

    //this method is responsible for taking all fee, if takeFee is true
    function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee, uint8 transferType) private {
        if(!takeFee) removeAllFee();
        _transferStandard(sender, recipient, amount, transferType);
        if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded");
    }

    function _transferStandard(address sender, address recipient, uint256 tAmount, uint8 transferType) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tOperations) = _getValues(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _takeLiquidity(tLiquidity);
        _takeOperations(tOperations, transferType);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

}
//to receive ETH from uniswapV2Router when swaping