const root = document.getElementById("root");
const url = "https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5";
let data = [
    {
        "ccy": "USD",
        "base_ccy": "UAH",
        "buy": "26.00000",
        "sale": "26.20000"
    },
    {
        "ccy": "EUR",
        "base_ccy": "UAH",
        "buy": "29.90000",
        "sale": "30.50000"
    },
    {
        "ccy": "RUR",
        "base_ccy": "UAH",
        "buy": "0.35000",
        "sale": "0.38000"
    },
    {
        "ccy": "BTC",
        "base_ccy": "USD",
        "buy": "58252.9497",
        "sale": "64384.8391"
    }
]
let currentCurrency = null;
let bankOperation = "buy";
let defaultValue = 100;

getCurrency();


function getCurrency() {
    fetch(url)
        .then((res) => {
                return res.json();
            },
            (err) => {
                currentCurrency = data[0];
                initApp(data, currentCurrency);
                console.log("some probloms");

            })
        .then((json) => {
                if (json) {
                    data = json;
                    currentCurrency = data[0];
                    initApp(json, currentCurrency);
                }
            }
        )
}

function initApp(data, currentCurrency) {

    const wrapper = document.createElement("div");
    wrapper.classList.add("wrapper");
    root.appendChild(wrapper);

    const informBlockWrapper = document.createElement("div");
    informBlockWrapper.classList.add("informBlockWrapper");
    wrapper.appendChild(informBlockWrapper);

    const currencyBlockWrapper = document.createElement("div");
    currencyBlockWrapper.classList.add("currencyBlockWrapper");
    informBlockWrapper.appendChild(currencyBlockWrapper);
    for (let i = 0; i < 3; i++) {
        const currencyBlock = document.createElement("div");
        currencyBlock.classList.add("currencyBlock");
        currencyBlock.innerText = `${data[i].ccy}`;
        currencyBlockWrapper.appendChild(currencyBlock);
        currencyBlock.addEventListener("click", chooseCurrency);
    }

    const exchangeRatesWrapper = document.createElement("div");
    exchangeRatesWrapper.classList.add("currencyBlockWrapperValue");
    informBlockWrapper.appendChild(exchangeRatesWrapper);

    for (let i = 0; i < 3; i++) {
        const exchangeRates = document.createElement("div");
        exchangeRates.classList.add("currencyBlockValue");
        exchangeRatesWrapper.appendChild(exchangeRates);
        for (let j = 0; j < 1; j++) {
            const buySaleCell = document.createElement("div");
            buySaleCell.classList.add("currencyBlockItem");
            buySaleCell.innerText = `${Number(data[i].buy).toFixed(2)} /  ${Number(data[i].sale).toFixed(2)}`;
            exchangeRates.appendChild(buySaleCell);
        }
    }
    const tableHeader = document.createElement("div");
    tableHeader.classList.add("tableHeader");
    wrapper.appendChild(tableHeader);

    const titleHeaderLeft = document.createElement("div");
    titleHeaderLeft.classList.add("blockTitle");
    titleHeaderLeft.innerText = "Отдаю";
    tableHeader.appendChild(titleHeaderLeft);

    const titleHeaderRight = document.createElement("div");
    titleHeaderRight.classList.add("titleHeaderRight", "blockTitle");
    titleHeaderRight.innerText = "Получаю";
    tableHeader.appendChild(titleHeaderRight);

    const converterWrapper = document.createElement("div");
    converterWrapper.classList.add("converterWrapper");
    wrapper.appendChild(converterWrapper);

    updateTable(currentCurrency)
}

function updateTable() {
    if (bankOperation === "buy") {
        leftBlock();
        centerBlock();
        rightBlock();
    } else {
        if (bankOperation === "sale") {
            rightBlock();
            centerBlock();
            leftBlock();
        }
    }
}

function leftBlock() {
    const converterWrapper = document.querySelector(".converterWrapper");

    const converterBlockLeft = document.createElement("div");
    converterBlockLeft.classList.add("converterBlock");
    converterWrapper.appendChild(converterBlockLeft);

    const converterBlokTitleSell = document.createElement("div");
    converterBlokTitleSell.classList.add("converterBlockTitle");
    converterBlokTitleSell.innerText = `${currentCurrency.ccy}`;
    converterBlockLeft.appendChild(converterBlokTitleSell);

    const converterCurrencySell = document.createElement("input");
    converterCurrencySell.classList.add("converterCurrency", "sell");
    converterCurrencySell.value = defaultValue;
    converterBlockLeft.appendChild(converterCurrencySell);
    converterCurrencySell.addEventListener("keyup", inputHandler);

    const converterBlockInfoSell = document.createElement("div");
    converterBlockInfoSell.classList.add("converterBlockInfo");
    converterBlockInfoSell.innerText = `1 ${currentCurrency.ccy} = ${Number(currentCurrency[bankOperation]).toFixed(2)} UAH`;
    converterBlockLeft.appendChild(converterBlockInfoSell);

}

function centerBlock() {
    const converterWrapper = document.querySelector(".converterWrapper");

    const converterBlockCenter = document.createElement("div");
    converterBlockCenter.classList.add("converterBlockCenter");
    converterWrapper.appendChild(converterBlockCenter);
    const icon = document.createElement("i");
    icon.classList.add("fas");
    icon.classList.add("fa-sync-alt");
    icon.addEventListener("click", swapCurrency);
    converterBlockCenter.appendChild(icon);
}

function rightBlock() {
    const converterWrapper = document.querySelector(".converterWrapper");

    const converterBlockRight = document.createElement("div");
    converterBlockRight.classList.add("converterBlock");
    converterWrapper.appendChild(converterBlockRight);

    const converterBlokTitleBuy = document.createElement("div");
    converterBlokTitleBuy.classList.add("converterBlockTitle");
    converterBlokTitleBuy.innerText = "UAH";
    converterBlockRight.appendChild(converterBlokTitleBuy);

    const converterCurrencyBuy = document.createElement("input");
    converterCurrencyBuy.classList.add("converterCurrency", "buy");

    converterCurrencyBuy.value = defaultValue * Number(currentCurrency[bankOperation]);
    converterCurrencyBuy.addEventListener("keyup", inputHandler);
    converterBlockRight.appendChild(converterCurrencyBuy);

    const converterBlockInfoBuy = document.createElement("div");
    converterBlockInfoBuy.classList.add("converterBlockInfo");
    converterBlockInfoBuy.innerText = `1 UAH = ${(1 / Number(currentCurrency[bankOperation])).toFixed(2)} ${currentCurrency.ccy}`;
    converterBlockRight.appendChild(converterBlockInfoBuy);
}

function chooseCurrency(event) {
    switch (event.target.innerText) {
        case "USD":
            currentCurrency = data[0];
            break
        case "EUR":
            currentCurrency = data[1];
            break;
        case "RUR":
            currentCurrency = data[2];
            break;
    }
    const converterWrapper = document.querySelector(".converterWrapper")
    converterWrapper.innerHTML = "";
    updateTable(currentCurrency);
}

function inputHandler(event) {
    let buyInput = document.querySelector(".buy");
    let sellInput = document.querySelector(".sell");
    let value = event.target.value;

    if (event.target.classList.contains("sell")) {
        if (isNaN(+event.target.value)) {
            buyInput.value = "Wrong value";
        } else {
            buyInput.value = (Number(value) * Number(currentCurrency[bankOperation])).toFixed(2);
        }
    }
    if (event.target.classList.contains("buy")) {
        if (isNaN(+event.target.value)) {
            sellInput.value = "Wrong value";
        } else {
            sellInput.value = (Number(value) / Number(currentCurrency[bankOperation])).toFixed(2);
        }
    }
}

function swapCurrency() {
    const converterWrapper = document.querySelector(".converterWrapper");
    converterWrapper.innerHTML = "";
    if (bankOperation === "buy") {
        bankOperation = "sale";

    } else {
        bankOperation = "buy";
    }
    updateTable();
}

