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

 Copyright 2014 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 "FolderSettings.h"

#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>

#include "fstream_mars_fix.h"

#include "Folder.h"
#include "Request.h"
#include "Tokenizer.h"

FolderSettings::FolderSettings(Folder* folder) :
    folder_(folder),
    fileName_("._mv_viewinfo_")
{
    read();
}

Desktop::FolderViewMode FolderSettings::viewMode()
{
    return viewMode_;
}

int FolderSettings::iconSize()
{
    return iconSize_;
}

void FolderSettings::setViewModeAndSize(Desktop::FolderViewMode viewMode, int iconSize)
{
    viewMode_ = viewMode;
    iconSize_ = iconSize;
    write();
}

void FolderSettings::setViewMode(Desktop::FolderViewMode v)
{
    viewMode_ = v;
    write();
}

void FolderSettings::setIconSize(int v)
{
    iconSize_ = v;
    write();
}

Desktop::FolderViewMode FolderSettings::toViewMode(int val)
{
    auto vm = static_cast<Desktop::FolderViewMode>(val);
    if (vm == Desktop::IconViewMode || vm == Desktop::SimpleViewMode ||
        vm == Desktop::DetailedViewMode) {
        return vm;
    }

    return Desktop::IconViewMode;
}

bool FolderSettings::hasFile()
{
    Path p = folder_->path().add(fileName_).str();
    return (p.exists() && !p.locked());
}

void FolderSettings::read()
{
    std::string path = folder_->path().add(fileName_).str();

    std::ifstream in(path.c_str());

    // Read the param file
    if (in.good()) {
        std::string line;

        Tokenizer parse(" ");
        std::vector<std::string> n;

        if (getline(in, line)) {
            parse(line, n);
            if (n.size() >= 2) {
                int vm = 0;

                std::istringstream issX(n[0]);
                issX >> vm;
                viewMode_ = FolderSettings::toViewMode(vm);

                std::istringstream issY(n[1]);
                issY >> iconSize_;
            }
        }
    }

    // If there is no param file we try to read the dot file
    else {
        Folder* parent = folder_->parent();
        if (!parent)
            return;

        Path parentPath = parent->path();
        Path dot = parentPath.add("." + folder_->name());
        Request dotInfo(dot);

        if (!dotInfo) {
            if (folder_->isLink()) {
                char buf[1024];
                int count = readlink(folder_->path().str().c_str(), buf, sizeof(buf));
                if (count > 0) {
                    buf[count] = '\0';
                    Path lnkP(buf);
                    dot = lnkP.directory().add("." + folder_->name());
                    dotInfo = Request(dot);
                }
            }
        }

        if (dotInfo) {
            if (const char* m = dotInfo("SMALL_ICONS")) {
                if (strcmp(m, "TRUE") == 0) {
                    viewMode_ = Desktop::SimpleViewMode;
                    iconSize_ = 16;
                    halfSizeImported_ = true;
                }
            }
        }
        else {
            readDefaults();
        }

        // Save the settings
        write();
    }
}

void FolderSettings::write()
{
    std::string path = folder_->path().add(fileName_).str();
    std::ofstream out;
    out.open(path.c_str());
    if (!out.good())
        return;

    out << static_cast<int>(viewMode_) << " " << iconSize_ << std::endl;
    out.close();
}

void FolderSettings::setDefaults(Desktop::FolderViewMode mode, int iconSize)
{
    MvRequest r = MvApplication::getPreferences();

    std::string str;

    switch (mode) {
        case Desktop::IconViewMode:
            str = "CLASSIC_ICON_VIEW";
            break;
        case Desktop::SimpleViewMode:
            str = "SIMPLE_ICON_VIEW";
            break;
        case Desktop::DetailedViewMode:
            str = "DETAILED_ICON_VIEW";
            break;
        default:
            break;
    }

    r("DEFAULT_VIEW_MODE") = str.c_str();
    r("DEFAULT_ICON_SIZE") = iconSize;

    MvApplication::setPreferences(r);
}

void FolderSettings::readDefaults()
{
    viewMode_ = FolderSettings::defaultViewMode();
    iconSize_ = FolderSettings::defaultIconSize();
}

Desktop::FolderViewMode FolderSettings::defaultViewMode()
{
    MvRequest r = MvApplication::getExpandedPreferences();

    if (const char* c = r("DEFAULT_VIEW_MODE")) {
        std::string str(c);
        std::transform(str.begin(), str.end(), str.begin(), ::tolower);

        if (str == "CLASSIC_ICON_VIEW")
            return Desktop::IconViewMode;
        else if (str == "SIMPLE_ICON_VIEW")
            return Desktop::SimpleViewMode;
        else if (str == "DETAILED_VIEW")
            return Desktop::DetailedViewMode;
    }

    return Desktop::IconViewMode;
}

int FolderSettings::defaultIconSize()
{
    MvRequest r = MvApplication::getExpandedPreferences();

    if (const char* c = r("DEFAULT_ICON_SIZE")) {
        int v = atoi(c);
        if (v > 0 && v < 200)
            return v;
    }

    return 32;
}
