contract OnePlanetCarbonCredit is ERC20Interface, Owned, SafeMath {
    string public symbol;
    string public  name;
    uint8 public decimals;
    uint public _totalSupply;
    uint public startDate;
    uint public bonusEnds;
    uint public endDate;
    uint public _maxSupply;
    uint256 public bonus1;
    uint256 public bonus2;
    uint256 public bonus3;
    uint public updateInterval;
    uint public currentIntervalRound;
    AggregatorV3Interface internal priceFeed;
    uint public ethPrice;
    uint public tokenPrice;
	address payable public oracleAddress;
	address public retireAddress;

    event CarbonOffset(string message);

    mapping(address => uint) balances;
    mapping(address => mapping(address => uint)) allowed;


    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------
    constructor() public {
        symbol = "1PLCO2";
        name = "1PLANET Carbon Credit";
        decimals = 18;
        bonusEnds = now + 1 weeks;
        endDate = now + 2000 weeks;
        _maxSupply = 150000000000000000000000000; // 150M tokens maximum supply = 150M metric tons CO2e
        bonus1 = 500000000000000000000; // bonus 1 5% = 500 tokens
        bonus2 = 1000000000000000000000; // bonus 2 10% = 1000 tokens
        bonus3 = 2500000000000000000000; // bonus 3 15% = 2500 tokens
		oracleAddress = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
		retireAddress = 0x0000000000000000000000000000000000000000;
		priceFeed = AggregatorV3Interface(oracleAddress);
        //priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); mainNet
    }

    // ------------------------------------------------------------------------
    // Total supply
    // ------------------------------------------------------------------------
    function totalSupply() public override view returns (uint) {
        return _totalSupply  - balances[address(0)];
    }
	
    function maxSupply() public view returns (uint) {
        return _maxSupply;
    }

    // ------------------------------------------------------------------------
    // Get the token balance for account `tokenOwner`
    // ------------------------------------------------------------------------
    function balanceOf(address tokenOwner) public override view returns (uint balance) {
        return balances[tokenOwner];
    }

    // ------------------------------------------------------------------------
    // Transfer the balance from token owner's account to `to` account
    // - Owner's account must have sufficient balance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transfer(address to, uint tokens) public override returns (bool success) {
        balances[msg.sender] = safeSub(balances[msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        emit Transfer(msg.sender, to, tokens);
        return true;
    }

    // ------------------------------------------------------------------------
    // Token owner can approve for `spender` to transferFrom(...) `tokens`
    // from the token owner's account
    //
    // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
    // recommends that there are no checks for the approval double-spend attack
    // as this should be implemented in user interfaces
    // ------------------------------------------------------------------------
    function approve(address spender, uint tokens) public override returns (bool success) {
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        return true;
    }

    // ------------------------------------------------------------------------
    // Transfer `tokens` from the `from` account to the `to` account
    //
    // The calling account must already have sufficient tokens approve(...)-d
    // for spending from the `from` account and
    // - From account must have sufficient balance to transfer
    // - Spender must have sufficient allowance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
        balances[from] = safeSub(balances[from], tokens);
        allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        emit Transfer(from, to, tokens);
        return true;
    }


    // ------------------------------------------------------------------------
    // Returns the amount of tokens approved by the owner that can be
    // transferred to the spender's account
    // ------------------------------------------------------------------------
    function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
        return allowed[tokenOwner][spender];
    }


    // ------------------------------------------------------------------------
    // Token owner can approve for `spender` to transferFrom(...) `tokens`
    // from the token owner's account. The `spender` contract function
    // `receiveApproval(...)` is then executed
    // ------------------------------------------------------------------------
    function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
        return true;
    }

    // ------------------------------------------------------------------------
    // Send ETH to get 1PLCO2 tokens
    // ------------------------------------------------------------------------
    receive() external payable {
        require(now >= startDate && now <= endDate);
        uint256 weiAmount = msg.value;
        uint256 tokens = _getTokenAmount(weiAmount);
        if(tokens >= bonus1 && tokens < bonus2){
            tokens = safeMul(tokens, 105);
            tokens = safeDiv(tokens, 100);
        }
        if(tokens >= bonus2 && tokens < bonus3){
            tokens = safeMul(tokens, 110);
            tokens = safeDiv(tokens, 100);
        }
        if(tokens >= bonus3){
            tokens = safeMul(tokens, 115);
            tokens = safeDiv(tokens, 100);
        }
        require(_maxSupply >= safeAdd(_totalSupply, tokens), "Maximum token amount reached. No more tokens to sell");
        balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
        _totalSupply = safeAdd(_totalSupply, tokens);
        emit Transfer(address(0), msg.sender, tokens);
        owner.transfer(msg.value);
        currentIntervalRound = safeAdd(currentIntervalRound, 1);
        if(currentIntervalRound == updateInterval) {
            getLatestPrice();
            currentIntervalRound = 0;
        }
    }

    function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
        uint256 temp = safeMul(weiAmount, ethPrice);
        temp = safeDiv(temp, 100);
        temp = safeDiv(temp, tokenPrice);
        temp = safeMul(temp, 100);
        return temp;
    }

    function setOnePLpriceInt(uint price) public onlyOwner {
        tokenPrice = price;
    }
	
	function updateOracleAddress(address payable newOracleAddress) public onlyOwner {
        oracleAddress = newOracleAddress;
        priceFeed = AggregatorV3Interface(oracleAddress);
	}

    function setRetireAddress(address newAddress) public onlyOwner {
        retireAddress = newAddress;
    }

    function setUpdateInterval(uint interval) public onlyOwner {
        updateInterval = interval;
    }

    function genAndSendTokens(address to, uint tokens) public onlyOwner returns (bool success) {
        require(now >= startDate && now <= endDate);
        require(_maxSupply >= safeAdd(_totalSupply, tokens));
        balances[to] = safeAdd(balances[to], tokens);
        _totalSupply = safeAdd(_totalSupply, tokens);
        emit Transfer(address(0), to, tokens);
        return true;
    }

    //-----------------------------------------------------
    // Returns the latest Chainlink Oracle ETH USD price
    //-----------------------------------------------------
    function getLatestPrice() public {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // If the round is not complete yet, timestamp is 0
        require(timeStamp > 0, "Round not complete");
        ethPrice = safeDiv(uint(price), 1000000);
    }

    function updateEthPriceManually(uint price) public onlyOwner {
        ethPrice = price;
    }

    function topUpBalance() public payable {
    }

    function withdrawFromBalance() public onlyOwner {
        owner.transfer(address(this).balance);
    }
    
    //-------------------------------------------------------------------------------------------
    // Enables dApps to generate custom messages for carbon offsetting applications with 1PLCO2
    // Can be used by third-party developers
    //-------------------------------------------------------------------------------------------
    function retireOnePL(uint tokens, string memory message) public returns (bool success) {
        transfer(retireAddress, tokens);
        emit CarbonOffset(message);
        return true;
    }

    // ------------------------------------------------------------------------
    // Owner can transfer out any accidentally sent ERC20 tokens
    // ------------------------------------------------------------------------
    function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
        return ERC20Interface(tokenAddress).transfer(owner, tokens);
    }
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Send ETH to get 1PLCO2 tokens
// ------------------------------------------------------------------------