// модуль для работы с элементами управления

// объект для удобного получения элементов
// при обращении к атрибуту объекта вызывается нужная функция для поиска элемента
export const cntrls = {
    table: document.querySelector("#items-table tbody"),
    button: document.getElementById("items-add"),
    form: document.getElementById("items-form"),
    lineId: document.getElementById("items-line-id"),
    categoryInput: document.getElementById("item"),
    nameInput: document.getElementById("name"),
    authorInput: document.getElementById("author"),
    yearInput: document.getElementById("year"),
    imageInput: document.getElementById("image"),
    imagePreview: document.getElementById("image-preview"),
};

// Дефолтное превью
export const imagePlaceholder = "https://via.placeholder.com/200";

// функция создает тег option для select (для списков категорий, авторов и т. д.)
// <option value="" selected>name</option>
export function createOption(name, value = "", isSelected = false) {
    const option = document.createElement("option");
    option.value = value || "";
    option.selected = isSelected;
    option.text = name;
    return option;
}

// функция создает ссылку (a) для таблицы
// содержимое тега a заполняется необходимой иконкой (icon)
// при нажатии вызывается callback
// ссылка "оборачивается" тегом td
// <td><a href="#" onclick="callback()"><i class="fa-solid icon"></i></a></td>
function createTableAnchor(icon, callback) {
    const i = document.createElement("i");
    i.classList.add("fa-solid", icon);
    const a = document.createElement("a");
    a.href = "#";
    a.appendChild(i);
    a.onclick = (event) => {
        // чтобы в URL не добавлялась решетка
        event.preventDefault();
        event.stopPropagation();
        callback();
    };
    const td = document.createElement("td");
    td.appendChild(a);
    return td;
}

// функция создает колонку таблицы с текстом value
// <td>value</td>
function createTableColumn(value) {
    const td = document.createElement("td");
    td.textContent = value;
    return td;
}

// функция создает строку таблицы
export function createTableRow(book, index, editPageCallback, deleteCallback) {
    const rowNumber = document.createElement("th");
    rowNumber.scope = "row";
    rowNumber.textContent = index + 1;
    const row = document.createElement("tr");
    row.id = `line-${book.id}`;
    row.appendChild(rowNumber);
    row.appendChild(createTableColumn(book.categories.name));
    row.appendChild(createTableColumn(book.name));
    row.appendChild(createTableColumn(book.authors.name));
    row.appendChild(createTableColumn(book.year));
    row.appendChild(createTableAnchor("fa-pen-to-square", editPageCallback));
    row.appendChild(createTableAnchor("fa-trash", deleteCallback));
    return row;
}