/* SPDX-License-Identifier: GPL-3.0-or-later
 * SPDX-FileCopyrightText: 2023-2024 Soren Stoutner <soren@stoutner.com>
 *
 * This file is part of Privacy Browser PC <https://www.stoutner.com/privacy-browser-pc/>.
 *
 * This program 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.
 *
 * This program 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
 * this program.  If not, see <https://www.gnu.org/licenses/>.
 */

// Application headers.
#include "AddFolderDialog.h"
#include "ui_AddFolderDialog.h"
#include "databases/BookmarksDatabase.h"
#include "helpers/FolderHelper.h"
#include "structs/BookmarkStruct.h"

// Qt toolkit headers.
#include <QFileDialog>

// Construct the class.
AddFolderDialog::AddFolderDialog(QWidget *parentWidgetPointer, const QIcon &currentWebsiteFavoriteIcon, const double parentFolderId) : QDialog(parentWidgetPointer)
{
    // Set the window title.
    setWindowTitle(i18nc("The add folder dialog window title.", "Add Folder"));

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

    // Instantiate the add folder dialog UI.
    Ui::AddFolderDialog addFolderDialogUi;

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

    // Get handles for the widgets.
    defaultFolderIconRadioButtonPointer = addFolderDialogUi.defaultFolderIconRadioButton;
    currentWebsiteFavoriteIconRadioButtonPointer = addFolderDialogUi.currentWebsiteFavoriteIconRadioButton;
    customFolderIconRadioButtonPointer = addFolderDialogUi.customFolderIconRadioButton;
    parentFolderTreeWidgetPointer = addFolderDialogUi.parentFolderTreeWidget;
    folderNameLineEditPointer = addFolderDialogUi.folderNameLineEdit;
    QPushButton *browseButtonPointer = addFolderDialogUi.browseButton;
    QDialogButtonBox *dialogButtonBoxPointer = addFolderDialogUi.dialogButtonBox;

    // Set the default favorite icon.
    currentWebsiteFavoriteIconRadioButtonPointer->setIcon(currentWebsiteFavoriteIcon);

    // 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();

    // Focus the folder name line edit.
    folderNameLineEditPointer->setFocus();

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

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

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

    // Update the UI when the folder name changes.
    connect(folderNameLineEditPointer, SIGNAL(textEdited(const QString&)), this, SLOT(updateUi(const QString&)));

    // Set the initial UI status.
    updateUi(folderNameLineEditPointer->text());
}

void AddFolderDialog::addFolder()
{
    // Get the parent folder ID.
    QList<QTreeWidgetItem*> selectedFoldersList = parentFolderTreeWidgetPointer->selectedItems();

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

    // Create a favorite icon.
    QIcon favoriteIcon;

    // Get the favorite icon.
    if (defaultFolderIconRadioButtonPointer->isChecked())  // The default folder icon is checked.
        favoriteIcon = defaultFolderIconRadioButtonPointer->icon();
    else if (currentWebsiteFavoriteIconRadioButtonPointer->isChecked())  // The current website favorite icon is checked.
        favoriteIcon = currentWebsiteFavoriteIconRadioButtonPointer->icon();
    else  // The custom folder icon is checked.
        favoriteIcon = customFolderIconRadioButtonPointer->icon();

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

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

    // Add the folder.
    BookmarksDatabase::addFolder(bookmarkStructPointer);

    // Update the list of bookmarks in the menu and toolbar.
    Q_EMIT folderAdded();

    // Close the dialog.
    close();
}

void AddFolderDialog::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.
        customFolderIconRadioButtonPointer->setIcon(QIcon(imageFileString));

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

void AddFolderDialog::updateUi(const QString &newFolderName)
{
    // Set the status of the add button based on the
    addButtonPointer->setEnabled(!newFolderName.isEmpty());
}
