/*
 * Copyright 2023-2024 Soren Stoutner <soren@stoutner.com>.
 *
 * This file is part of Privacy Browser PC <https://www.stoutner.com/privacy-browser-pc>.
 *
 * Privacy Browser PC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Privacy Browser PC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Privacy Browser PC.  If not, see <http://www.gnu.org/licenses/>.
 */

// Application headers.
#include "AddBookmarkDialog.h"
#include "ui_AddBookmarkDialog.h"
#include "databases/BookmarksDatabase.h"

// KDE Framework headers.
#include <KLocalizedString>

// Qt toolkit headers.
#include <QFileDialog>
#include <QPushButton>

// Construct the class.
AddBookmarkDialog::AddBookmarkDialog(QWidget *parentWidgetPointer, const QString &bookmarkName, const QString &bookmarkUrl, const QIcon &favoriteIcon, const double parentFolderId) :
                                     QDialog(parentWidgetPointer)
{
    // Set the window title.
    setWindowTitle(i18nc("The add bookmark dialog window title.", "Add Bookmark"));

    // Set the window modality.
    setWindowModality(Qt::WindowModality::ApplicationModal);

    // Instantiate the add bookmark dialog UI.
    Ui::AddBookmarkDialog addBookmarkDialogUi;

    // Setup the UI.
    addBookmarkDialogUi.setupUi(this);

    // Get handles for the widgets.
    websiteFavoriteIconRadioButtonPointer = addBookmarkDialogUi.websiteFavoriteIconRadioButton;
    customFavoriteIconRadioButtonPointer = addBookmarkDialogUi.customFavoriteIconRadioButton;
    parentFolderTreeWidgetPointer = addBookmarkDialogUi.parentFolderTreeWidget;
    bookmarkNameLineEditPointer = addBookmarkDialogUi.bookmarkNameLineEdit;
    bookmarkUrlLineEditPointer = addBookmarkDialogUi.bookmarkUrlLineEdit;
    QPushButton *browseButtonPointer = addBookmarkDialogUi.browseButton;
    QDialogButtonBox *dialogButtonBoxPointer = addBookmarkDialogUi.dialogButtonBox;

    // Set the icons.
    websiteFavoriteIconRadioButtonPointer->setIcon(favoriteIcon);
    customFavoriteIconRadioButtonPointer->setIcon(QIcon::fromTheme(QLatin1String("globe"), QIcon::fromTheme(QLatin1String("applications-internet"))));

    // Instantiate a folder helper.
    folderHelperPointer = new FolderHelper();

    // Set the parent folder tree widget column count.
    parentFolderTreeWidgetPointer->setColumnCount(2);

    // Hide the second column.
    parentFolderTreeWidgetPointer->hideColumn(folderHelperPointer->FOLDER_ID_COLUMN);

    // Set the column header.
    parentFolderTreeWidgetPointer->setHeaderLabel(i18nc("The folder tree widget header", "Select Parent Folder"));

    // Create a bookmarks tree widget item.
    QTreeWidgetItem *bookmarksTreeWidgetItemPointer = new QTreeWidgetItem();

    // Populate the bookmarks tree widget item.
    bookmarksTreeWidgetItemPointer->setText(folderHelperPointer->FOLDER_NAME_COLUMN, i18nc("The bookmarks root tree widget name", "Bookmarks"));
    bookmarksTreeWidgetItemPointer->setIcon(folderHelperPointer->FOLDER_NAME_COLUMN, QIcon::fromTheme(QLatin1String("bookmarks"), QIcon::fromTheme(QLatin1String("bookmark-new"))));
    bookmarksTreeWidgetItemPointer->setText(folderHelperPointer->FOLDER_ID_COLUMN, QLatin1String("0"));

    // Add the bookmarks tree widget item to the root of the tree.
    parentFolderTreeWidgetPointer->addTopLevelItem(bookmarksTreeWidgetItemPointer);

    // Select the root bookmarks folder if it is the initial parent folder.
    if (parentFolderId == 0)
        bookmarksTreeWidgetItemPointer->setSelected(true);

    // Populate the subfolders.
    folderHelperPointer->populateSubfolders(bookmarksTreeWidgetItemPointer, parentFolderId);

    // Open all the folders.
    parentFolderTreeWidgetPointer->expandAll();

    // Populate the line edits.
    bookmarkNameLineEditPointer->setText(bookmarkName);
    bookmarkUrlLineEditPointer->setText(bookmarkUrl);

    // Scroll to the beginning of the bookmark URL line edit.
    bookmarkUrlLineEditPointer->setCursorPosition(0);

    // Focus the bookmark name line edit.
    bookmarkNameLineEditPointer->setFocus();

    // Add buttons to the dialog button box.
    addButtonPointer = dialogButtonBoxPointer->addButton(i18nc("The add bookmark button", "Add"), QDialogButtonBox::AcceptRole);

    // Set the button icons.
    addButtonPointer->setIcon(QIcon::fromTheme("list-add"));

    // Connect the buttons.
    connect(browseButtonPointer, SIGNAL(clicked()), this, SLOT(browse()));
    connect(dialogButtonBoxPointer, SIGNAL(accepted()), this, SLOT(addBookmark()));
    connect(dialogButtonBoxPointer, SIGNAL(rejected()), this, SLOT(reject()));

    // Update the UI when the line edits change.
    connect(bookmarkNameLineEditPointer, SIGNAL(textEdited(const QString&)), this, SLOT(updateUi()));
    connect(bookmarkUrlLineEditPointer, SIGNAL(textEdited(const QString&)), this, SLOT(updateUi()));

    // Set the initial UI status.
    updateUi();
}

void AddBookmarkDialog::addBookmark()
{
    // Get the selected folders list.
    QList<QTreeWidgetItem*> selectedFoldersList = parentFolderTreeWidgetPointer->selectedItems();

    // Get the selected folder.
    QTreeWidgetItem *selectedFolderPointer = selectedFoldersList.first();

    // Get the favorite icon.
    QIcon favoriteIcon = websiteFavoriteIconRadioButtonPointer->isChecked() ? websiteFavoriteIconRadioButtonPointer->icon() : customFavoriteIconRadioButtonPointer->icon();

    // Create a bookmark struct.
    BookmarkStruct *bookmarkStructPointer = new BookmarkStruct;

    // Populate the bookmark struct.
    bookmarkStructPointer->name = bookmarkNameLineEditPointer->text();
    bookmarkStructPointer->url = bookmarkUrlLineEditPointer->text();
    bookmarkStructPointer->parentFolderId = selectedFolderPointer->text(folderHelperPointer->FOLDER_ID_COLUMN).toDouble();
    bookmarkStructPointer->favoriteIcon = favoriteIcon;

    // Add the bookmark.
    BookmarksDatabase::addBookmark(bookmarkStructPointer);

    // Update the list of bookmarks in the menu and toolbar.
    emit bookmarkAdded();

    // Close the dialog.
    close();
}

void AddBookmarkDialog::browse()
{
    // Get an image file string from the user.
    QString imageFileString = QFileDialog::getOpenFileName(this, tr("Favorite Icon Image"), QDir::homePath(),
                                                           tr("Image Files — *.bmp, *.gif, *.jpg, *.jpeg, *.png, *.svg (*.bmp *.gif *.jpg *.jpeg *.png *.svg);;All Files (*)"));

    // Check to see if an image file string was returned.  This will be empty if the user selected cancel.
    if (!imageFileString.isEmpty())
    {
        // Set the custom favorite icon.
        customFavoriteIconRadioButtonPointer->setIcon(QIcon(imageFileString));

        // Check the custom favorite icon radio button.
        customFavoriteIconRadioButtonPointer->setChecked(true);
    }
}

void AddBookmarkDialog::updateUi()
{
    // Update the add button status
    if (bookmarkNameLineEditPointer->text().isEmpty() || bookmarkUrlLineEditPointer->text().isEmpty())  // At least one of the line edits is empty.
    {
        // Disable the add button.
        addButtonPointer->setEnabled(false);
    }
    else  // Both of the line edits are populated.
    {
        // Enable the add button.
        addButtonPointer->setEnabled(true);
    }
}
