/***************************** 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 "FamilyObject.h"

#include "Request.h"
#include "MvIconLanguage.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "FamilyScanner.h"
#include "MvLog.h"

FamilyObject::FamilyObject(Folder* parent, const IconClass& kind,
                           const std::string& name, IconInfo* info) :
    StandardObject(parent, kind, name, info),
    scanner_(FamilyScanner::find(kind))
{
    // MvLog().info() << MV_FN_INFO << "name=" << name << " kind=" << kind.name() << " class=" << class_->name();
}

FamilyObject::~FamilyObject() = default;


Request FamilyObject::request() const
{
    // return language().expand(selected());
    // return first();
    return iconClass().language().expand(second());
}

void FamilyObject::setRequest(const Request& actRec)
{
    Request r = actRec;
    Request f;

    // If actRec only contains the panel request
    if (r.getVerb() != class_->name()) {
        f = first();
    }
    else {
        f = r.justOneRequest();
        r.advance();
    }

    f = f + IconClass::find(r.getVerb()).language().expand(r, EXPAND_NO_DEFAULT | EXPAND_2ND_NAME);

    //    MvLog().info() << MV_FN_INFO << "req=";
    //    f.print();

    f.save(path());
}

Request FamilyObject::first() const
{
    Request r(path());
    return class_->language().expand(r.justOneRequest());
}

Request FamilyObject::second() const
{
    Request r(path());
    if (scanner_.validate(r)) {
        // r.print();
        r.save(path());
    }
    r.advance();
    return r;
}

Request FamilyObject::requestForVerb(const std::string& verb) const
{
    Request f = first();
    if (f.getVerb() == verb)
        return f;
    else {
        f = second();
        if (f.getVerb() == verb)
            return f;
    }

    return {};
}

const IconClass& FamilyObject::editorClass() const
{
    return *class_;
}

const IconClass& FamilyObject::iconClass() const
{
    return IconClass::find(second().getVerb());
}

void FamilyObject::createFiles()
{
    IconObject::createFiles();
    Path p = path();
    if (!p.exists()) {
        Request r;
        if (scanner_.validate(r)) {
            // r.print();
            r.save(path());
        }
    }
}

static IconMaker<FamilyObject> maker("Family");
