package com.sourcefellows.oneintention;


import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {

        Main main = new Main();
        main.parseDocumentAndCalculatePriceAndStoreInDB("<tax-value>1.19</tax-value><price-value>10.2</price-value><product-id>1</product-id>");

    }

    public void parseDocumentAndCalculatePriceAndStoreInDB(String data) {
        int beginIdx = data.indexOf("<tax-value>");
        int endIdx = data.indexOf("</tax-value>");
        String taxValueString = data.substring(beginIdx + 11, endIdx);
        float taxValue = Float.parseFloat(taxValueString);
        beginIdx = data.indexOf("<price-value>");
        endIdx = data.indexOf("</price-value>");
        String productPriceString = data.substring(beginIdx + 13, endIdx);
        float productPrice = Float.parseFloat(productPriceString);
        String price = String.format("%.2f", taxValue * productPrice);
        String sqlString = "UPDATE products SET price =";
        sqlString += price;
        sqlString += " WHERE id = ";
        beginIdx = data.indexOf("<product-id>");
        endIdx = data.indexOf("</product-id>");
        sqlString += data.substring(beginIdx + 12, endIdx);
        Database.execute(sqlString);
    }

public void updateProductPrice(String data) {

    Product product = Product.fromString(data);
    BigDecimal grossPrice =
            product.getNetPrice().multiply(product.getTaxValue());
    Database.updateGrossPrice(product, grossPrice);

}

}
