/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQLayerDialog.h"

#include "MvIconDataBase.h"
#include "MvPath.hpp"
#include "MvRequest.h"
#include "MvRequestUtil.hpp"
#include "Presentable.h"
#include "Root.h"

MvQLayerDialog::MvQLayerDialog(int iconId, QString startDir, QWidget* parent) :
    MvQFileDialog(startDir, "Save as", parent),
    iconId_(iconId)
{
    // Set widget mode behaviour to "Save As"
    this->setAcceptMode(QFileDialog::AcceptSave);
}

// Destructor
MvQLayerDialog::~MvQLayerDialog() = default;

// Callback from the SAVE button
void MvQLayerDialog::accept()
{
    // Get filename from the dialog
    QString iconName = selectedFiles().at(0);

    // Get Presentable SuperPage
    Presentable* pres = Root::Instance().FindSuperPage();

    // Retrieve icon from the DataBase and save it on disk
    MvIcon mvIcon;
    MvIconDataBase& dataBase = pres->IconDataBase();
    if (dataBase.FindIcon(iconId_, mvIcon)) {
        // Save icon on disk
        MvRequest iconReq = mvIcon.Request();
        std::string siconName = iconName.toStdString();
        std::string fullPath = MakeUserPath(siconName);

        // Remove all hiden parameters before saving the icon
        metview::RemoveParameters(iconReq, "_");
        iconReq.save(fullPath.c_str());
    }

    hide();
}

void MvQLayerDialog::reject()
{
    QDialog::reject();
}
