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

 Copyright 2013 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 "MvQRecentIcons.h"

#include <QSettings>
#include "MvQMethods.h"

int MvQRecentIcons::maxNum_ = 20;
QStringList MvQRecentIcons::items_;
QList<RecentIconsObserver*> MvQRecentIcons::observers_;

MvQRecentIcons::MvQRecentIcons() = default;

void MvQRecentIcons::init()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-Desktop-RecentIcons");

    settings.beginGroup("main");
    if (settings.contains("recentIcons")) {
        items_ = settings.value("recentIcons").toStringList();
    }
    settings.endGroup();
}

void MvQRecentIcons::save()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-Desktop-RecentIcons");

    // We have to clear it not to remember all the previous settings
    settings.clear();
    settings.beginGroup("main");
    settings.setValue("recentIcons", items_);
    settings.endGroup();
}

void MvQRecentIcons::add(QString name)
{
    if (items_.contains(name)) {
        items_.removeAll(name);
        items_ << name;
    }
    else {
        if (items_.count() >= maxNum_)
            items_.takeFirst();

        items_ << name;
    }

    foreach (RecentIconsObserver* o, observers_)
        o->notifyRecentChanged();
}

void MvQRecentIcons::removeObserver(RecentIconsObserver* o)
{
    observers_.removeAll(o);
}

static MvQRecentIcons recentIcons;
