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

 Copyright 2022 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 "FilePropertyDialog.h"

#include <QFileInfo>
#include <QSettings>

#include "IconDescription.h"
#include "IconObject.h"
#include "MvQIconProvider.h"
#include "MvQMethods.h"
#include "MvQTheme.h"
#include "MvQStreamOper.h"
#include "MvLog.h"
#include "Path.h"

#include "ui_FilePropertyDialog.h"


FilePropertyDialog::FilePropertyDialog(QWidget* parent) :
    QDialog(parent),
    ui_(new Ui::FilePropertyDialog)
{
    ui_->setupUi(this);
    readSettings();
}

FilePropertyDialog::~FilePropertyDialog()
{
    writeSettings();
}

void FilePropertyDialog::setItem(IconObject* item)
{
    path_.clear();
    linkPath_.clear();
    if (item) {
        ui_->iconLabel->setPixmap(MvQIconProvider::pixmap(item, 32));
        path_ = item->path().str();
        auto txt = IconDescription::Instance()->table(item, true);
        if (item->isLink()) {
            linkPath_ = item->path().symlinkTarget();
            ui_->linkEdit->setText(QString::fromStdString(linkPath_));
            txt += "<hr>";
        }
        else {
            ui_->linkLabel->hide();
            ui_->linkEdit->hide();
        }
        ui_->infoLabel->setText(txt);
    }
}

void FilePropertyDialog::accept()
{
    if (!linkPath_.empty()) {
        Path p(path_);
        p.changeSymlink(Path(ui_->linkEdit->text().toStdString()));
        if (auto obj = IconObject::search(path_)) {
            obj->updateStateInfo();
        }
    }
    QDialog::accept();
}

void FilePropertyDialog::writeSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "Desktop-FilePropertyDialog");

    // We have to clear it not to remember all the previous windows
    settings.clear();

    settings.beginGroup("main");
    settings.setValue("size", size());
    settings.endGroup();
}

void FilePropertyDialog::readSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "Desktop-FilePropertyDialog");

    settings.beginGroup("main");
    if (settings.contains("size")) {
        resize(settings.value("size").toSize());
    }
    else {
        resize(QSize(400, 380));
    }

    settings.endGroup();
}
