/***************************** 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 "WsObject.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "IconInfo.h"
#include "Editor.h"
#include "MvLog.h"
#include "MvIconLanguage.h"
#include "WsDecoder.h"

#include <QFile>
#include "MvQStreamOper.h"

Request WsObject::request() const
{
    MvRequest r;
    if (fileType_ == NoFileType) {
        if (!readFromJson(r)) {
            readFromRequest(r);
        }
    }
    else if (fileType_ == JsonFileType) {
        readFromJson(r);
    }
    else if (fileType_ == RequestFileType) {
        readFromRequest(r);
    }

    if (!r) {
        r = MvRequest(className().c_str());
    }

    // We need to make sure the request is always expanded. For visualisation in
    // uPlot and for decoding we need the full request
    return language().expand(r.justOneRequest());
}

// Try to read it as geojson
bool WsObject::readFromJson(MvRequest& r) const
{
    WsDecoder::toRequest(path().str(), r);
    //    MvLog().dbg() << MV_FN_INFO << " r=";
    //    r.print();
    if (r) {
        if (r.getVerb() && strcmp(r.getVerb(), className().c_str()) == 0) {
            fileType_ = JsonFileType;
            return true;
        }
    }
    r = MvRequest();
    return false;
}

// Try to read it as MvRequest
bool WsObject::readFromRequest(MvRequest& r) const
{
    r = path().loadRequest();
    if (r.getVerb() && strcmp(r.getVerb(), className().c_str()) == 0) {
        fileType_ = RequestFileType;
        return true;
    }
    r = MvRequest();
    return false;
}

void WsObject::setRequest(const Request& r)
{
    //    MvLog().dbg() << MV_FN_INFO << fileType_ << "r=";
    //    r.print();
    if (fileType_ != RequestFileType) {
        fileType_ = JsonFileType;
        QJsonDocument doc;
        WsDecoder::toJson(r, doc);
        //        MvLog().dbg() << "WRITE=" << path().str();
        //        r.print();
        //        MvLog().dbg() << "JSON=" << QString(doc.toJson());
        QFile f(QString::fromStdString(path().str()));
        if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
            f.write(doc.toJson());
        }
        f.close();
    }
}

bool WsObject::checkRequest()
{
    return true;
}

void WsObject::createFiles()
{
    //    MvLog().dbg() << MV_FN_INFO;
    Path p = path();
    if (!p.exists()) {
        Request r(className().c_str());
        setRequest(language().expand(r.justOneRequest()));
    }
}

static IconMaker<WsObject> maker1("WeatherSymbol");
