/* 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 "EditFolderDialog.h"
#include "ui_EditFolderDialog.h"
#include "databases/BookmarksDatabase.h"

// Qt toolkit headers.
#include <QFileDialog>

// Construct the class.
EditFolderDialog::EditFolderDialog(QWidget *parentWidgetPointer, const int databaseId, QIcon &currentWebsiteFavoriteIcon) : QDialog(parentWidgetPointer), folderDatabaseId(databaseId)
{
    // Set the window title.
    setWindowTitle(i18nc("The edit folder dialog window title.", "Edit Folder"));

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

    // Instantiate the edit folder dialog UI.
    Ui::EditFolderDialog editFolderDialogUi;

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

    // Get handles for the widgets.
    currentFolderIconRadioButtonPointer = editFolderDialogUi.currentFolderIconRadioButton;
    defaultFolderIconRadioButtonPointer = editFolderDialogUi.defaultFolderIconRadioButton;
    currentWebsiteFavoriteIconRadioButtonPointer = editFolderDialogUi.currentWebsiteFavoriteIconRadioButton;
    customFolderIconRadioButtonPointer = editFolderDialogUi.customFolderIconRadioButton;
    parentFolderTreeWidgetPointer = editFolderDialogUi.parentFolderTreeWidget;
    folderNameLineEditPointer = editFolderDialogUi.folderNameLineEdit;
    QPushButton *browseButtonPointer = editFolderDialogUi.browseButton;
    QDialogButtonBox *dialogButtonBoxPointer = editFolderDialogUi.dialogButtonBox;
    saveButtonPointer = dialogButtonBoxPointer->button(QDialogButtonBox::Save);

    // Get the folder bookmark struct.
    folderBookmarkStructPointer = BookmarksDatabase::getBookmark(databaseId);

    // Set the folder icons.
    currentFolderIconRadioButtonPointer->setIcon(folderBookmarkStructPointer->favoriteIcon);
    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 (folderBookmarkStructPointer->parentFolderId == 0)
        bookmarksTreeWidgetItemPointer->setSelected(true);

    // Populate the subfolders, except for the one being edited.
    folderHelperPointer->populateSubfoldersExcept(databaseId, bookmarksTreeWidgetItemPointer, folderBookmarkStructPointer->parentFolderId);

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

    // Populate the line edits.
    folderNameLineEditPointer->setText(folderBookmarkStructPointer->name);

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

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

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

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

void EditFolderDialog::browse()
{
    // Get an image file string from the user.
    QString imageFileString = QFileDialog::getOpenFileName(this, i18nc("The browse for folder icon dialog header", "Folder Icon Image"), QDir::homePath(),
                              i18nc("The browse for image files filter", "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 folder icon.
        customFolderIconRadioButtonPointer->setIcon(QIcon(imageFileString));

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

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

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

    // Get the parent folder ID.
    double parentFolderId = selectedFolderPointer->text(folderHelperPointer->FOLDER_ID_COLUMN).toDouble();

    // Determine if it has moved to a new folder.
    bool movedToNewFolder =  parentFolderId != folderBookmarkStructPointer->parentFolderId;

    // Get the original display order.
    int displayOrder = folderBookmarkStructPointer->displayOrder;

    // Get the new display order if the parent folder has changed.
    if (movedToNewFolder)
        displayOrder = BookmarksDatabase::getFolderItemCount(parentFolderId);

    // Create a favorite icon.
    QIcon favoriteIcon;

    // Get the favorite icon.
    if (currentFolderIconRadioButtonPointer->isChecked())  // The current folder icon is checked.
        favoriteIcon = currentFolderIconRadioButtonPointer->icon();
    else 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 favorite icon is checked.
        favoriteIcon = customFolderIconRadioButtonPointer->icon();

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

    // Populate the bookmark struct.
    updatedBookmarkStructPointer->databaseId = folderDatabaseId;
    updatedBookmarkStructPointer->name = folderNameLineEditPointer->text();
    updatedBookmarkStructPointer->parentFolderId = parentFolderId;
    updatedBookmarkStructPointer->displayOrder = displayOrder;
    updatedBookmarkStructPointer->favoriteIcon = favoriteIcon;

    // Update the folder.
    BookmarksDatabase::updateBookmark(updatedBookmarkStructPointer);

    // Update the display order of all the items in the previous folder if it has moved to a new folder.
    if (movedToNewFolder)
        BookmarksDatabase::updateFolderContentsDisplayOrder(folderBookmarkStructPointer->parentFolderId);

    // Emit the folder saved signal.
    Q_EMIT folderSaved();

    // Close the dialog.
    close();
}

void EditFolderDialog::updateUi()
{
    // Set the status of the save button.
    saveButtonPointer->setEnabled(!folderNameLineEditPointer->text().isEmpty());
}
