/***************************************************************************
 * SPDX-FileCopyrightText: 2024 S. MANKOWSKI stephane@mankowski.fr
 * SPDX-FileCopyrightText: 2024 G. DE BURE support@mankowski.fr
 * SPDX-License-Identifier: GPL-3.0-or-later
 ***************************************************************************/
/** @file
 * This file is Skrooge plugin for GSB import / export.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgimportplugingsb.h"

#include <kcompressiondevice.h>
#include <klocalizedstring.h>
#include <kpluginfactory.h>

#include "skgbankincludes.h"
#include "skgimportexportmanager.h"
#include "skgobjectbase.h"
#include "skgpayeeobject.h"
#include "skgservices.h"
#include "skgtraces.h"

/**
 * This plugin factory.
 */
K_PLUGIN_CLASS_WITH_JSON(SKGImportPluginGsb, "metadata.json")

SKGImportPluginGsb::SKGImportPluginGsb(QObject* iImporter, const QVariantList& iArg)
    : SKGImportPlugin(iImporter)
{
    SKGTRACEINFUNC(10)
    Q_UNUSED(iArg)
}

SKGImportPluginGsb::~SKGImportPluginGsb()
    = default;

bool SKGImportPluginGsb::isImportPossible()
{
    SKGTRACEINFUNC(10)
    return (m_importer->getDocument() == nullptr ? true : m_importer->getFileNameExtension() == QLatin1String("GSB"));
}

SKGError SKGImportPluginGsb::importFile()
{
    if (m_importer->getDocument() == nullptr) {
        return SKGError(ERR_ABORT, i18nc("Error message", "Invalid parameters"));
    }
    SKGError err;
    SKGTRACEINFUNCRC(2, err)

    // Initialisation
    // Open file
    KCompressionDevice file(m_importer->getLocalFileName(), KCompressionDevice::GZip);
    if (!file.open(QIODevice::ReadOnly)) {
        err.setReturnCode(ERR_INVALIDARG).setMessage(i18nc("Error message",  "Open file '%1' failed", m_importer->getFileName().toDisplayString()));
    } else {
        QDomDocument doc;

        // Set the file without uncompression
        QString errorMsg;
        int errorLine = 0;
        int errorCol = 0;
        bool contentOK = false;        
#ifdef SKG_QT6
        const auto& content = QString::fromUtf8(file.readAll());
        const auto& result= doc.setContent(content);

        contentOK = !!result;
        errorLine =result.errorLine;
        errorCol =result.errorColumn;
        errorMsg =result.errorMessage;
#else        
        contentOK = doc.setContent(file.readAll(), &errorMsg, &errorLine, &errorCol);
#endif
        file.close();

        // Get root
        QDomElement docElem = doc.documentElement();

        if (!contentOK) {
            err.setReturnCode(ERR_ABORT).setMessage(i18nc("Error message",  "%1-%2: '%3'", errorLine, errorCol, errorMsg));
        } else {
            // Check version
            QDomElement general = docElem.firstChildElement(QLatin1String("General"));
            if (general.isNull()) {
                err.setReturnCode(ERR_ABORT).setMessage(i18nc("Error message",  "Bad version of Grisbi document. Version must be >= 0.6.0"));
                contentOK = false;
            }
        }

        if (!contentOK) {
            err.addError(ERR_INVALIDARG, i18nc("Error message",  "Invalid XML content in file '%1'", m_importer->getFileName().toDisplayString()));
        } else {
            err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import %1 file", "GSB"), 10);

            QMap<QString, SKGUnitObject> mapIdUnit;
            QMap<QString, SKGBankObject> mapIdBank;
            QMap<QString, SKGAccountObject> mapIdAccount;
            QMap<QString, SKGCategoryObject> mapIdCategory;
            QMap<QString, SKGOperationObject> mapIdOperation;
            QMap<QString, SKGPayeeObject> mapIdPayee;
            QMap<QString, QString> mapIdMode;
            QMap<QString, QString> mapIdBudgetCat;

            // Step 1-Create units
            IFOK(err) {
                QDomNodeList currencyList = docElem.elementsByTagName(QLatin1String("Currency"));
                int nb = currencyList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import units"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement currency = currencyList.at(i).toElement();

                    // Creation of the units
                    SKGUnitObject unitObj(m_importer->getDocument());
                    IFOKDO(err, unitObj.setName(getAttribute(currency, QLatin1String("Na"))))
                    IFOKDO(err, unitObj.setSymbol(getAttribute(currency, QLatin1String("Co"))))
                    IFOKDO(err, unitObj.setNumberDecimal(SKGServices::stringToInt(getAttribute(currency, QLatin1String("Fl")))))
                    IFOKDO(err, unitObj.save())

                    mapIdUnit[getAttribute(currency,  QLatin1String("Nb"))] = unitObj;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(1))

            // Step 2-Create banks
            IFOK(err) {
                QDomNodeList bankList = docElem.elementsByTagName(QLatin1String("Bank"));
                int nb = bankList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import banks"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement bank = bankList.at(i).toElement();

                    // Creation of the banks
                    SKGBankObject bankObj(m_importer->getDocument());
                    IFOKDO(err, bankObj.setName(getAttribute(bank, QLatin1String("Na"))))
                    IFOKDO(err, bankObj.setNumber(getAttribute(bank, QLatin1String("BIC"))))
                    IFOKDO(err, bankObj.save())

                    mapIdBank[getAttribute(bank,  QLatin1String("Nb"))] = bankObj;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(2))

            // Step 3-Create accounts
            SKGBankObject bankDefault(m_importer->getDocument());
            IFOKDO(err, bankDefault.setName(QLatin1String("GRISBI")))
            IFOKDO(err, bankDefault.save())
            IFOK(err) {
                QDomNodeList accountList = docElem.elementsByTagName(QLatin1String("Account"));
                int nb = accountList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import accounts"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement account = accountList.at(i).toElement();

                    // Creation of the account
                    SKGAccountObject accountObj;
                    SKGBankObject bank = mapIdBank[getAttribute(account,  QLatin1String("Bank"))];
                    if (!bank.exist()) {
                        bank = bankDefault;
                    }
                    IFOKDO(err, bank.addAccount(accountObj))
                    IFOKDO(err, accountObj.setName(getAttribute(account, QLatin1String("Name"))))
                    IFOKDO(err, accountObj.setNumber(getAttribute(account, QLatin1String("Bank_account_number"))))
                    IFOKDO(err, accountObj.setComment(getAttribute(account, QLatin1String("Comment"))))
                    IFOKDO(err, accountObj.setAgencyAddress(getAttribute(account, QLatin1String("Owner_address"))))
                    IFOKDO(err, accountObj.setMinLimitAmount(SKGServices::stringToDouble(getAttribute(account, QLatin1String("Minimum_authorised_balance")))))
                    IFOKDO(err, accountObj.minLimitAmountEnabled(accountObj.getMinLimitAmount() != 0.0))
                    IFOKDO(err, accountObj.setClosed(getAttribute(account, QLatin1String("Closed_account")) != QLatin1String("0")))
                    IFOKDO(err, accountObj.save())
                    IFOKDO(err, accountObj.setInitialBalance(SKGServices::stringToDouble(getAttribute(account, QLatin1String("Initial_balance"))), mapIdUnit[getAttribute(account, QLatin1String("Currency"))]))

                    mapIdAccount[getAttribute(account,  QLatin1String("Number"))] = accountObj;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(3))

            // Step 4-Get payees
            IFOK(err) {
                QDomNodeList partyList = docElem.elementsByTagName(QLatin1String("Party"));
                int nb = partyList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import payees"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get payee object
                    QDomElement party = partyList.at(i).toElement();
                    SKGPayeeObject payeeObject;
                    err = SKGPayeeObject::createPayee(m_importer->getDocument(), getAttribute(party,  QLatin1String("Na")), payeeObject);
                    mapIdPayee[getAttribute(party,  QLatin1String("Nb"))] = payeeObject;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(4))

            // Step 5-Get payement mode
            IFOK(err) {
                QDomNodeList paymentList = docElem.elementsByTagName(QLatin1String("Payment"));
                int nb = paymentList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import payment mode"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get mode object
                    QDomElement payment = paymentList.at(i).toElement();
                    mapIdMode[getAttribute(payment,  QLatin1String("Number"))] = getAttribute(payment,  QLatin1String("Name"));

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(5))

            // Step 6-Create categories
            IFOK(err) {
                QDomNodeList categoryList = docElem.elementsByTagName(QLatin1String("Category"));
                int nb = categoryList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import categories"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement category = categoryList.at(i).toElement();

                    // Creation of the categories
                    SKGCategoryObject catObj(m_importer->getDocument());
                    IFOKDO(err, catObj.setName(getAttribute(category, QLatin1String("Na"))))
                    IFOKDO(err, catObj.save())

                    QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(category,  QLatin1String("Nb"))));
                    mapIdCategory[id] = catObj;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(6))

            // Step 7-Create subcategories
            IFOK(err) {
                QDomNodeList categoryList = docElem.elementsByTagName(QLatin1String("Sub_category"));
                int nb = categoryList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import categories"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement category = categoryList.at(i).toElement();

                    // Creation of the subcategories
                    SKGCategoryObject catParentObj = mapIdCategory[SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(category,  QLatin1String("Nbc"))))];
                    SKGCategoryObject catObj;
                    IFOKDO(err, catParentObj.addCategory(catObj))
                    IFOKDO(err, catObj.setName(getAttribute(category, QLatin1String("Na"))))
                    IFOKDO(err, catObj.save())

                    QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(category,  QLatin1String("Nbc"))) + SKGServices::stringToInt(getAttribute(category,  QLatin1String("Nb"))));
                    mapIdCategory[id] = catObj;

                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(7))

            // Step 8-Index of budget categories
            IFOK(err) {
                QDomNodeList budgetaryList = docElem.elementsByTagName(QLatin1String("Budgetary"));
                int nb = budgetaryList.count();
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement budgetary = budgetaryList.at(i).toElement();
                    QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(budgetary,  QLatin1String("Nb"))));
                    mapIdBudgetCat[id] = getAttribute(budgetary,  QLatin1String("Na"));
                }
            }
            IFOK(err) {
                QDomNodeList budgetaryList = docElem.elementsByTagName(QLatin1String("Sub_budgetary"));
                int nb = budgetaryList.count();
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement budgetary = budgetaryList.at(i).toElement();
                    QString id1 = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(budgetary,  QLatin1String("Nb"))));
                    QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(budgetary,  QLatin1String("Nbb"))) + SKGServices::stringToInt(getAttribute(budgetary,  QLatin1String("Nb"))));
                    mapIdBudgetCat[id] = mapIdBudgetCat[id1] % OBJECTSEPARATOR % getAttribute(budgetary,  QLatin1String("Na"));
                }
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(8))

            // Step 9-Create transaction
            IFOK(err) {
                QDomNodeList transactionList = docElem.elementsByTagName(QLatin1String("Transaction"));
                int nb = transactionList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import transactions"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement transaction = transactionList.at(i).toElement();

                    // Creation of the transaction
                    SKGOperationObject opObj;
                    QString parentOpId = getAttribute(transaction,  QLatin1String("Mo"));
                    if (parentOpId == QLatin1String("0")) {
                        SKGAccountObject account = mapIdAccount[getAttribute(transaction,  QLatin1String("Ac"))];
                        IFOKDO(err, account.addOperation(opObj, true))
                        IFOKDO(err, opObj.setDate(QDate::fromString(getAttribute(transaction, QLatin1String("Dt")), QLatin1String("MM/dd/yyyy"))))
                        IFOKDO(err, opObj.setUnit(mapIdUnit[ getAttribute(transaction, QLatin1String("Cu"))]))
                        IFOKDO(err, opObj.setPayee(mapIdPayee[ getAttribute(transaction, QLatin1String("Pa"))]))
                        IFOKDO(err, opObj.setMode(mapIdMode[getAttribute(transaction, QLatin1String("Pn"))]))
                        IFOKDO(err, opObj.setNumber(getAttribute(transaction, QLatin1String("Pc"))))
                        IFOKDO(err, opObj.setComment(getAttribute(transaction, QLatin1String("No"))))
                        IFOKDO(err, opObj.setImported(true))
                        IFOKDO(err, opObj.setImportID("GSB-" % getAttribute(transaction, QLatin1String("Nb"))))
                        IFOKDO(err, opObj.setStatus(getAttribute(transaction, QLatin1String("Re")) == QLatin1String("0") ? SKGOperationObject::NONE : SKGOperationObject::CHECKED))
                        IFOKDO(err, opObj.setGroupOperation(mapIdOperation[getAttribute(transaction, QLatin1String("Trt"))]))
                        IFOKDO(err, opObj.save())
                    } else {
                        opObj = mapIdOperation[parentOpId];
                    }

                    // Budgetary allocation
                    IFOK(err) {
                        int sbu = SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Sbu")));
                        QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Bu"))) + qMax(sbu, 0));
                        QString buCat = mapIdBudgetCat[id];
                        if (!buCat.isEmpty()) {
                            err = opObj.setProperty(i18nc("Noun", "Budgetary allocation"), buCat);
                            IFOKDO(err, opObj.save())
                        }
                    }

                    if (getAttribute(transaction,  QLatin1String("Br")) == QLatin1String("0")) {
                        SKGSubOperationObject subObj;
                        IFOKDO(err, opObj.addSubOperation(subObj))
                        QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Ca"))) + SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Sca"))));
                        IFOKDO(err, subObj.setCategory(mapIdCategory[id]))
                        IFOKDO(err, subObj.setComment(getAttribute(transaction, QLatin1String("No"))))
                        IFOKDO(err, subObj.setQuantity(SKGServices::stringToDouble(getAttribute(transaction, QLatin1String("Am")))))
                        IFOKDO(err, subObj.save())
                    }

                    // Fiscal year
                    IFOK(err) {
                        QString fiscalYear = getAttribute(transaction,  QLatin1String("Vo"));
                        if (!fiscalYear.isEmpty()) {
                            err = opObj.setProperty(i18nc("Noun", "Fiscal year"), fiscalYear);
                            IFOKDO(err, opObj.save())
                        }
                    }

                    if (parentOpId == QLatin1String("0")) {
                        mapIdOperation[getAttribute(transaction,  QLatin1String("Nb"))] = opObj;
                    }

                    if (!err && i % 500 == 0) {
                        err = m_importer->getDocument()->executeSqliteOrder(QLatin1String("ANALYZE"));
                    }
                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(9))

            // Step 10-Create scheduled transaction
            IFOK(err) {
                QDomNodeList scheduledList = docElem.elementsByTagName(QLatin1String("Scheduled"));
                int nb = scheduledList.count();
                err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import scheduled transactions"), nb);
                for (int i = 0; !err && i < nb; ++i) {
                    // Get account object
                    QDomElement transaction = scheduledList.at(i).toElement();

                    // Creation of the transaction
                    SKGAccountObject account = mapIdAccount[getAttribute(transaction,  QLatin1String("Ac"))];
                    SKGOperationObject opObj;
                    IFOKDO(err, account.addOperation(opObj, true))
                    QDate firstDate = QDate::fromString(getAttribute(transaction,  QLatin1String("Dt")), QLatin1String("MM/dd/yyyy"));
                    IFOKDO(err, opObj.setDate(firstDate))
                    IFOKDO(err, opObj.setUnit(mapIdUnit[ getAttribute(transaction, QLatin1String("Cu"))]))
                    IFOKDO(err, opObj.setPayee(mapIdPayee[ getAttribute(transaction, QLatin1String("Pa"))]))
                    IFOKDO(err, opObj.setMode(mapIdMode[getAttribute(transaction, QLatin1String("Pn"))]))
                    IFOKDO(err, opObj.setNumber(getAttribute(transaction, QLatin1String("Pc"))))
                    IFOKDO(err, opObj.setComment(getAttribute(transaction, QLatin1String("No"))))
                    IFOKDO(err, opObj.setImported(true))
                    IFOKDO(err, opObj.setImportID("GSB-" % getAttribute(transaction, QLatin1String("Nb"))))
                    IFOKDO(err, opObj.setTemplate(true))
                    IFOKDO(err, opObj.save())

                    SKGSubOperationObject subObj;
                    IFOKDO(err, opObj.addSubOperation(subObj))
                    QString id = SKGServices::intToString(10000 * SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Ca"))) + SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Sca"))));
                    IFOKDO(err, subObj.setCategory(mapIdCategory[id]))
                    IFOKDO(err, subObj.setComment(getAttribute(transaction, QLatin1String("No"))))
                    IFOKDO(err, subObj.setQuantity(SKGServices::stringToDouble(getAttribute(transaction, QLatin1String("Am")))))
                    IFOKDO(err, subObj.save())

                    QString Tra = getAttribute(transaction,  QLatin1String("Tra"));
                    if (Tra != QLatin1String("0")) {
                        // This is a transfer
                        SKGOperationObject opObj2;
                        IFOKDO(err, opObj.duplicate(opObj2, opObj.getDate(), true))
                        IFOKDO(err, opObj2.setImported(true))
                        IFOKDO(err, opObj2.setImportID("GSB-" % getAttribute(transaction, QLatin1String("Nb")) % "_TR"))
                        IFOKDO(err, opObj2.save())

                        SKGObjectBase::SKGListSKGObjectBase subObjs2;
                        IFOKDO(err, opObj2.getSubOperations(subObjs2))
                        if (!err && !subObjs2.isEmpty()) {
                            SKGSubOperationObject subObj2(subObjs2.at(0));
                            err = subObj2.setQuantity(-subObj.getQuantity());
                            IFOKDO(err, subObj2.save())
                        }

                        // Group transactions
                        IFOKDO(err, opObj.setGroupOperation(opObj2))
                        IFOKDO(err, opObj.save())
                    }

                    // Create the schedule
                    SKGRecurrentOperationObject recuObj;
                    IFOKDO(err, opObj.addRecurrentOperation(recuObj))
                    IFOKDO(err, recuObj.setAutoWriteDays(0))
                    IFOKDO(err, recuObj.autoWriteEnabled(getAttribute(transaction, QLatin1String("Au")) != QLatin1String("0")))
                    IFOK(err) {
                        // text_frequency [] = { _("Once"), _("Weekly"), _("Monthly"), _("two months"), ("trimester"), _("Yearly"), _("Custom"), nullptr };
                        int occu = 1;
                        SKGRecurrentOperationObject::PeriodUnit period = SKGRecurrentOperationObject::DAY;
                        QString Pe = getAttribute(transaction,  QLatin1String("Pe"));
                        if (Pe == QLatin1String("0")) {
                            period = SKGRecurrentOperationObject::MONTH;
                            IFOKDO(err, recuObj.timeLimit(true))
                            IFOKDO(err, recuObj.setTimeLimit(1))

                        } else if (Pe == QLatin1String("1")) {
                            period = SKGRecurrentOperationObject::WEEK;
                        } else if (Pe == QLatin1String("2")) {
                            period = SKGRecurrentOperationObject::MONTH;
                        } else if (Pe == QLatin1String("3")) {
                            occu = 2;
                            period = SKGRecurrentOperationObject::MONTH;
                        } else if (Pe == QLatin1String("4")) {
                            occu = 3;
                            period = SKGRecurrentOperationObject::MONTH;
                        } else if (Pe == QLatin1String("5")) {
                            period = SKGRecurrentOperationObject::YEAR;
                        } else if (Pe == QLatin1String("6")) {
                            // text_frequency_user [] = { _("Days"), _("Weeks"), _("Months"), _("Years"), nullptr };
                            occu = SKGServices::stringToInt(getAttribute(transaction,  QLatin1String("Pep")));
                            QString Pei = getAttribute(transaction,  QLatin1String("Pei"));
                            if (Pei == QLatin1String("0")) {
                                period = SKGRecurrentOperationObject::DAY;
                            } else if (Pei == QLatin1String("1")) {
                                period = SKGRecurrentOperationObject::WEEK;
                            } else if (Pei == QLatin1String("2")) {
                                period = SKGRecurrentOperationObject::MONTH;
                            } else {
                                period = SKGRecurrentOperationObject::YEAR;
                            }
                        }

                        IFOKDO(err, recuObj.setPeriodUnit(period))
                        IFOKDO(err, recuObj.setPeriodIncrement(occu))

                        QString Dtl = getAttribute(transaction,  QLatin1String("Dtl"));
                        if (!err && !Dtl.isEmpty()) {
                            IFOKDO(err, recuObj.timeLimit(true))
                            IFOKDO(err, recuObj.setTimeLimit(QDate::fromString(Dtl, QLatin1String("MM/dd/yyyy"))))
                        }
                    }
                    IFOKDO(err, recuObj.save())

                    if (!err && i % 500 == 0) {
                        err = m_importer->getDocument()->executeSqliteOrder(QLatin1String("ANALYZE"));
                    }
                    IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
                }

                SKGENDTRANSACTION(m_importer->getDocument(),  err)
            }
            IFOKDO(err, m_importer->getDocument()->stepForward(10))

            SKGENDTRANSACTION(m_importer->getDocument(),  err)

            IFOKDO(err, m_importer->getDocument()->executeSqliteOrder(QLatin1String("ANALYZE")))
        }
    }

    return err;
}


QString SKGImportPluginGsb::getAttribute(const QDomElement& iElement, const QString& iAttribute)
{
    QString val = iElement.attribute(iAttribute);
    if (val == QLatin1String("(null)")) {
        val = QString();
    }
    return val;
}
QString SKGImportPluginGsb::getMimeTypeFilter() const
{
    return "*.gsb|" % i18nc("A file format", "Grisbi file");
}

#include <skgimportplugingsb.moc>
