##########################################################################
##                                                                      ##
## Copyright (C) 2011-2026 Lukas Spies                                  ##
## Contact: https://photoqt.org                                         ##
##                                                                      ##
## This file is part of PhotoQt.                                        ##
##                                                                      ##
## PhotoQt 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 2 of the License, or    ##
## (at your option) any later version.                                  ##
##                                                                      ##
## PhotoQt 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 PhotoQt. If not, see <http://www.gnu.org/licenses/>.      ##
##                                                                      ##
##########################################################################

import numpy as np
import sys
import sqlite3

import os

def get():

    conn = sqlite3.connect('../defaultsettings.db')

    dbtables = ['filedialog',
            'filetypes',
            'general',
            'imageview',
            'interface',
            'mainmenu',
            'mapview',
            'metadata',
            'slideshow',
            'thumbnails']

    cont_SOURCE = """/**************************************************************************
**                                                                      **
** Copyright (C) 2011-2026 Lukas Spies                                  **
** Contact: https://photoqt.org                                         **
**                                                                      **
** This file is part of PhotoQt.                                        **
**                                                                      **
** PhotoQt 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 2 of the License, or    **
** (at your option) any later version.                                  **
**                                                                      **
** PhotoQt 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 PhotoQt. If not, see <http://www.gnu.org/licenses/>.      **
**                                                                      **
**************************************************************************/

/**//**//**//**//**//**//**//**//**//**//**//**//**//**//**/
//
// WARNING
// THIS FILE IS AUTO GENERATED BY `misc/pqc_settings.py`.
// ANY CHANGES HERE WILL BE OVERWRITTEN AT SOME POINT!
//
/**//**//**//**//**//**//**//**//**//**//**//**//**//**//**/

#include <QJSValue>
#include <QMessageBox>
#include <qlogging.h>   // needed in this form to compile with Qt 6.2
#include <QApplication>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <pqc_settings.h>
#include <pqc_settingscpp.h>
#include <pqc_configfiles.h>
#include <pqc_notify_cpp.h>
#include <pqc_extensionshandler.h>

PQCSettings::PQCSettings(bool validateonly) {
    if(validateonly) {
        dbCommitTimer = nullptr;
        qDebug() << "THIS INSTANCE SHOULD ONLY BE USED FOR VALIDATING!";
    } else
        PQCSettings();
}

PQCSettings::PQCSettings() {

    QSqlDatabase dbDefault;

    // create and connect to default database
    if(QSqlDatabase::contains("defaultsettings"))
        dbDefault = QSqlDatabase::database("defaultsettings");
    else {
        if(QSqlDatabase::isDriverAvailable("QSQLITE3"))
            dbDefault = QSqlDatabase::addDatabase("QSQLITE3", "defaultsettings");
        else if(QSqlDatabase::isDriverAvailable("QSQLITE"))
            dbDefault = QSqlDatabase::addDatabase("QSQLITE", "defaultsettings");
    }
    QFile::remove(PQCConfigFiles::get().DEFAULTSETTINGS_DB());
    QFile::copy(":/defaultsettings.db", PQCConfigFiles::get().DEFAULTSETTINGS_DB());
    dbDefault.setDatabaseName(PQCConfigFiles::get().DEFAULTSETTINGS_DB());
    if(!dbDefault.open()) {
        qCritical() << "ERROR opening default database:" << (PQCConfigFiles::get().DEFAULTSETTINGS_DB());
        QMessageBox::critical(0, QApplication::translate("PQSettings", "ERROR opening database with default settings"),
                            QApplication::translate("PQSettings", "I tried hard, but I just cannot open the database of default settings.") + QApplication::translate("PQSettings", "Something went terribly wrong somewhere!"));
        return;
    }

    QSqlDatabase db = QSqlDatabase::database("settings");

    dbtables = QStringList() << "general"
                            << "interface"
                            << "imageview"
                            << "thumbnails"
                            << "mainmenu"
                            << "metadata"
                            << "filetypes"
                            << "filedialog"
                            << "slideshow"
                            << "mapview";

    readonly = false;

    if(!db.open()) {

        qWarning() << "ERROR opening database:" << db.lastError().text();
        qWarning() << "Will load read-only set of default settings";

        readonly = true;

    } else {

        QFileInfo infodb(PQCConfigFiles::get().USERSETTINGS_DB());

        readonly = false;
        if(!infodb.permission(QFileDevice::WriteOwner))
            readonly = true;

    }

    dbIsTransaction = false;
    dbCommitTimer = new QTimer();
    dbCommitTimer->setSingleShot(true);
    dbCommitTimer->setInterval(400);
#if __cplusplus >= 202002L
    connect(dbCommitTimer, &QTimer::timeout, this, [=, this]() {
#else
    connect(dbCommitTimer, &QTimer::timeout, this, [=]() {
#endif
        QSqlDatabase db = QSqlDatabase::database("settings");
        db.commit();
        PQCSettingsCPP::get().readDB();
        dbIsTransaction = false;
        if(db.lastError().text().trimmed().length())
            qWarning() << "ERROR committing database:" << db.lastError().text();
    });

    /******************************************************/

    // set up with all defaults
    setupFresh();

    /******************************************************/

    // then update with user settings (if applicable)
    QFileInfo info(PQCConfigFiles::get().USERSETTINGS_DB());
    if(!info.exists()) {
        if(!QFile::copy(":/usersettings.db", PQCConfigFiles::get().USERSETTINGS_DB()))
            qWarning() << "Unable to (re-)create default settings database";
        else {
            QFile file(PQCConfigFiles::get().USERSETTINGS_DB());
            file.setPermissions(file.permissions()|QFileDevice::WriteOwner);
        }
    } else
        readDB();

    /******************************************************/
    """

    ########################################
    # CHANGED SIGNAL CONNECTIONS
    ########################################

    for iC in range(2):

        if iC == 0:
            cont_SOURCE += """
#if __cplusplus >= 202002L
"""
        else:
            cont_SOURCE += """

#else
"""

        for tab in dbtables:

            c = conn.cursor()
            c.execute(f"SELECT `name`,`datatype` FROM {tab} ORDER BY `name`")
            data = c.fetchall()

            cont_SOURCE += f"""
    // table: {tab}"""
            for row in data:

                name = row[0]
                datatype = row[1]

                qtdatatpe = "QString"
                if datatype == "bool":
                    qtdatatpe = "bool"
                elif datatype == "int":
                    qtdatatpe = "int"
                elif datatype == "double":
                    qtdatatpe = "double"
                elif datatype == "list":
                    qtdatatpe = "QStringList"
                elif datatype == "point":
                    qtdatatpe = "QPoint"
                elif datatype == "size":
                    qtdatatpe = "QSize"

                cont_SOURCE += f"""
    connect(this, &PQCSettings::{tab}{name}Changed, this, [={", this" if iC == 0 else ""}]() {{ saveChangedValue(\"{tab}{name}\", m_{tab}{name}); }});"""


    cont_SOURCE += """

#endif

    /******************************************************/

#if __cplusplus >= 202002L
    connect(&PQCNotifyCPP::get(), &PQCNotifyCPP::disableColorSpaceSupport, this, [=, this]() {{ setImageviewColorSpaceEnable(false); }});
#else
    connect(&PQCNotifyCPP::get(), &PQCNotifyCPP::disableColorSpaceSupport, this, [=]() {{ setImageviewColorSpaceEnable(false); }});
#endif

}

PQCSettings::~PQCSettings() {{
    QSqlDatabase::removeDatabase("defaultsettings");
    QSqlDatabase::removeDatabase("settings");
    if(dbCommitTimer != nullptr) {{
        delete dbCommitTimer;
    }}
}}
"""

    return cont_SOURCE;
