/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "mainwindow.h"
#include "mapplication.h"
#include "treemodel.h"

#include "formbudget.h"
#include "formthird.h"
#include "formproduct.h"
#include "formelementlist.h"
#include "formthirdlist.h"
#include "forminvoiceinlist.h"
#include "formbudgetlist.h"
#include "utils/fiebdc.h"

//#include "QsfMainWindow.h"
#include "QMainWindow"
#include "QTabWidget"
#include "QMessageBox"


#if !SARIBBON_USE_3RDPARTY_FRAMELESSHELPER
#include "gui/SARibbon/src/SARibbonBar/SAFramelessHelper.h"
#endif
#include "gui/SARibbon/src/SARibbonBar/SARibbonApplicationButton.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonBar.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonButtonGroupWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCategory.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCheckBox.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonColorToolButton.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonComboBox.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCustomizeDialog.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCustomizeWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonGallery.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonLineEdit.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonMenu.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonPannel.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonQuickAccessBar.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonToolButton.h"
#include "gui/SARibbon/src/SARibbonBar/colorWidgets/SAColorGridWidget.h"
#include "gui/SARibbon/src/SARibbonBar/colorWidgets/SAColorPaletteGridWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonSystemButtonBar.h"
#include <QTextEdit>


#include <QFile>
#include <QFileDialog>
#include <QDockWidget>


MainWindow::MainWindow(QWidget *parent)
    : SARibbonMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);   //<<----------- pensar en esto

    //允许嵌套dock
    setDockNestingEnabled(true);
    setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
    setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);

    m_workspace = new QTabWidget;
    setCentralWidget(m_workspace);
    m_workspace->setTabsClosable(true);
    connect(m_workspace, &QTabWidget::tabCloseRequested, this, &MainWindow::tabCloseRequested);

    QStatusBar* statusBar = new QStatusBar();
    statusBar->setObjectName("QsfStatuBar");
    this->setStatusBar(statusBar);
    this->setStatusTip("Prueba: javier braña");
    this->setRibbonTheme(SARibbonTheme::RibbonThemeOffice2021Blue);



    SARibbonBar* ribbon = ribbonBar();
    ribbon->setContentsMargins(2, 0, 2, 0);

    QAbstractButton* btn = ribbon->applicationButton();
    if (!btn) {
        //! cn: SARibbonBar默认就会创建一个SARibbonApplicationButton，因此，在正常情况下，这个位置不会进入
        //! en: SARibbonBar creates a SARibbonApplicationButton by default. Therefore, under normal circumstances, this location will not enter
        btn = new SARibbonApplicationButton(this);
        ribbon->setApplicationButton(btn);
    }
    ribbon->applicationButton()->setText(("  &File  "));


    SARibbonCategory* categoryThirdParties = new SARibbonCategory();
    categoryThirdParties->setCategoryName(tr("Tercero"));
    categoryThirdParties->setObjectName(("categoryThirdParties"));
    ribbon->addCategoryPage(categoryThirdParties);

    SARibbonPannel* pannel1 = new SARibbonPannel(tr("pannel one"));
    pannel1->setObjectName("categoryThirdParties-pannel1");
    categoryThirdParties->addPannel(pannel1);
    QAction* actSave = createAction(tr("Save"), ":/resources/icons/save.svg");

    connect(actSave, &QAction::triggered, this, [ this ](bool b) {
        Q_UNUSED(b);
        this->createFormBudget();
    });

    pannel1->addLargeAction(actSave);

    SARibbonButtonGroupWidget* btnGroup1 = new SARibbonButtonGroupWidget(pannel1);
    btnGroup1->setObjectName("SARibbonButtonGroupWidget1");
    btnGroup1->setWindowTitle("SARibbonButtonGroupWidget1");
    btnGroup1->addAction(createAction(tr("Decrease Margin"), ":/resources/icons/brush.png"));
    btnGroup1->addAction(createAction(tr("Decrease Indent"), ":/resources/icons/add-file.svg"));
    btnGroup1->addAction(createAction(tr("Wrap Image Left"), ":/resources/icons/tag.svg"));
    btnGroup1->addAction(createAction(tr("Wrap Image Right"),":/resources/icons/recycle.svg"));
    pannel1->addWidget(btnGroup1, SARibbonPannelItem::Medium);

    SARibbonButtonGroupWidget* btnGroup2 = new SARibbonButtonGroupWidget(pannel1);
    btnGroup2->setObjectName("SARibbonButtonGroupWidget2");
    btnGroup2->setWindowTitle("SARibbonButtonGroupWidget2");
    btnGroup2->addAction(createAction(tr("Decrease Margin"), ":/resources/icons/brush.png"));
    btnGroup2->addAction(createAction(tr("Decrease Indent"), ":/resources/icons/add-file.svg"));
    btnGroup2->addAction(createAction(tr("Wrap Image Left"), ":/resources/icons/tag.svg"));
    btnGroup2->addAction(createAction(tr("Wrap Image Right"),":/resources/icons/recycle.svg"));
    pannel1->addWidget(btnGroup2, SARibbonPannelItem::Medium);

    // Nueva categoría para import/export
    SARibbonCategory* categoryIO = new SARibbonCategory();
    categoryIO->setCategoryName(tr("Import/Export"));
    categoryIO->setObjectName(("categoryIO"));
    ribbon->addCategoryPage(categoryIO);

    SARibbonPannel* pannelIO = new SARibbonPannel(tr("FIEBDC/BC3"));
    pannelIO->setObjectName("categoryIO-pannelFIEBDC");
    categoryIO->addPannel(pannelIO);

    QAction* actImportFIEBDC = createAction(tr("Import FIEBDC"), ":/resources/icons/import.svg");
    connect(actImportFIEBDC, &QAction::triggered, this, &MainWindow::importFIEBDCFile);
    pannelIO->addLargeAction(actImportFIEBDC);

    QAction* actExportBC3 = createAction(tr("Export BC3"), ":/resources/icons/export.svg");
    connect(actExportBC3, &QAction::triggered, this, &MainWindow::exportBC3File);
    pannelIO->addLargeAction(actExportBC3);




    SARibbonCategory* categoryDelete = new SARibbonCategory();
    categoryDelete->setCategoryName(("Delete"));
    categoryDelete->setObjectName(("categoryDelete"));
    ribbon->addCategoryPage(categoryDelete);
}


QDockWidget* MainWindow::createDockWidget( QString title, QString name, Qt::DockWidgetArea area )
{
    QDockWidget* tDock = new QDockWidget(title);
    tDock->setObjectName("dockWidget");
    tDock->setFloating(true);

    QWidget* docWid1 = new QWidget;
    docWid1->setObjectName("dockWidgetContents");
    tDock->setWidget(docWid1);
    return tDock;
}

QWidget* MainWindow::createWorkWidget( QString title, QString name )
{
    QWidget* tWidget = new QWidget();
    tWidget->setWindowTitle(title);
    m_workspace->addTab(tWidget, title);
    return tWidget;

}

void MainWindow::addWorkWidget(QWidget *tWidget, QString title)
{
    m_workspace->addTab(tWidget, (title == "") ? tWidget->windowTitle() : title);
    m_workspace->setCurrentIndex(m_workspace->count() - 1);
}

void MainWindow::setCompany(QString ID)
{

    setWindowTitle(ID);

    auto *form3 = new formElementList();
    QDockWidget *a = createDockWidget(form3->windowTitle(), form3->windowTitle(), Qt::LeftDockWidgetArea);
    a->setWidget(form3);
    addDockWidget(Qt::LeftDockWidgetArea, a);


    auto *form4 = new formThirdList();
    QDockWidget *b = createDockWidget(form4->windowTitle(), form4->windowTitle(), Qt::LeftDockWidgetArea);
    b->setWidget(form4);
    //addDockWidget(Qt::LeftDockWidgetArea, a);
    tabifyDockWidget(a, b);

    /*
    auto *form5 = new formInvoiceInList();
    a = createDockWidget(form5->windowTitle(), form5->windowTitle(), Qt::LeftDockWidgetArea);
    a->setWidget(form5);
    addDockWidget(Qt::LeftDockWidgetArea, a);*/

    auto *form6 = new FormBudgetList();
    QDockWidget *c = createDockWidget(form6->windowTitle(), form6->windowTitle(), Qt::RightDockWidgetArea);
    c->setWidget(form6);
    addDockWidget(Qt::RightDockWidgetArea, c);

}

formProduct * MainWindow::createFormProduct()
{
    auto *form = new formProduct();
    form->setWindowTitle("Nuevo Elemento");
    addWorkWidget(form, form->windowTitle());

    return form;
}

formThird * MainWindow::createFormThird()
{
    auto *form = new formThird();
    form->setWindowTitle("Nuevo Tercero");
    addWorkWidget(form, form->windowTitle());

    return form;
}

formBudget *MainWindow::createFormBudget()
{
    auto *form = new formBudget();
    form->setWindowTitle("Nuevo Presupusto");
    addWorkWidget(form, form->windowTitle());

    return form;
}

QAction* MainWindow::createAction(const QString& text, const QString& iconurl, const QString& objName)
{
    QAction* act = new QAction(this);
    act->setText(text);
    act->setIcon(QIcon(iconurl));
    if (objName == "")
        act->setObjectName(text);
    else
        act->setObjectName(objName);
    return act;
}





void MainWindow::tabCloseRequested(int index)
{
    qDebug() << m_workspace->widget(index);
    auto * form = static_cast<formBase*>(m_workspace->widget(index));
    if (form->needsave())
    {
        QMessageBox msgBox;
        msgBox.setText("Se necesita guardar el documento.");
        msgBox.setInformativeText("Do you want to save your changes?");
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        int ret = msgBox.exec();
        if (ret == QMessageBox::Cancel)
            return;
        else if (ret == QMessageBox::Save)
            form->save();
    }
    form->closeDocument();
    m_workspace->removeTab(index);
}


void MainWindow::importFIEBDCFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Import FIEBDC File"), "", tr("FIEBDC Files (*.fiebdc);;All Files (*)"));
    if (filename.isEmpty())
        return;

    FIEBDC fiebdc;
    if (fiebdc.load(filename)) {
        // Create a new budget form and import the data
        formBudget* form = new formBudget();
        form->setWindowTitle(tr("Presupuesto importado desde FIEBDC"));
        
        // Clear any existing data in the form
        form->clearContents();
        
        // Add each concept from the FIEBDC file as a row in the budget
        for (int i = 0; i < fiebdc.getConceptCount(); ++i) {
            const FIEBDC::Concept& fiebdcConcept = fiebdc.getConcept(i);
            
            // Insert a new row with the concept data using public method
            form->insertRowWithData(
                fiebdcConcept.code,
                fiebdcConcept.summary,
                fiebdcConcept.unit,
                fiebdcConcept.price,
                fiebdcConcept.type
            );
        }
                               tr("FIEBDC file imported successfully.\n%1 concepts were imported.").arg(fiebdc.getConceptCount()));
    } else {
        QMessageBox::warning(this, tr("Import Failed"), 
                           tr("Could not import FIEBDC file: %1").arg(filename));
    }
}

void MainWindow::exportBC3File()
{
    // Get the current active budget form
    QWidget* currentWidget = m_workspace->currentWidget();
    formBudget* budgetForm = qobject_cast<formBudget*>(currentWidget);
    
    if (!budgetForm) {
        QMessageBox::warning(this, tr("Export Failed"), 
                           tr("No budget form is currently active."));
        return;
    }
    
    QString filename = QFileDialog::getSaveFileName(this, tr("Export BC3 File"), "", tr("BC3 Files (*.bc3);;XML Files (*.xml);;All Files (*)"));
    if (filename.isEmpty())
        return;
    
    // Collect data from the budget form to create FIEBDC concepts
    FIEBDC fiebdc;
    
    int rowCount = budgetForm->ui->tableElements->rowCount();
    for (int row = 0; row < rowCount; ++row) {
        FIEBDC::Concept concept;
        
        // Get data from table
        concept.code = budgetForm->ui->tableElements->item(row, 0) ? budgetForm->ui->tableElements->item(row, 0)->text() : "";
        concept.summary = budgetForm->ui->tableElements->item(row, 1) ? budgetForm->ui->tableElements->item(row, 1)->text() : "";
        concept.unit = budgetForm->ui->tableElements->item(row, 2) ? budgetForm->ui->tableElements->item(row, 2)->text() : "";
        concept.price = budgetForm->ui->tableElements->item(row, 4) ? budgetForm->ui->tableElements->item(row, 4)->text() : "0.0";
        
        // Determine type based on some logic or default to OT
        // For now, we'll use a simple mapping or default
        concept.type = "OT"; // Other as default
        
        fiebdc.addConcept(concept);
    }
    
    if (fiebdc.exportToBC3(filename)) {
        QMessageBox::information(this, tr("Export Successful"), 
                               tr("BC3 file exported successfully.\n%1 concepts were exported.").arg(fiebdc.getConceptCount()));
    } else {
        QMessageBox::warning(this, tr("Export Failed"), 
                           tr("Could not export BC3 file: %1").arg(filename));
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    dApp->quit();
}
