/***************************** 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 <Assertions.hpp>
#include <MvRequest.h>

#include "DataBuilder.h"
#include "ObjectList.h"
#include "PmContext.h"
#include "MvDecoder.h"
#include "SuperPage.h"
#include "Root.h"
#include "Task.h"

// This is the singleton instance of the prototype
static DataBuilder dataBuilderInstance("DataBuilder");

Presentable*
DataBuilder::Execute(PmContext& context)
{
    MvRequest dataReq = context.InRequest();

    // Make sure the macro is generated in current dir, even when defaults are used.
    const char* fullName = (const char*)dataReq("_NAME");
    const char* path = nullptr;
    if (fullName)
        path = mdirname(fullName);

    // Creation of a new PlotPage and associated pages
    Presentable* superpage = nullptr;
    MvRequest defaultSuperPage = ObjectList::CreateDefaultRequest("PLOT_SUPERPAGE", 0, path);

    // Create default page and add view to this request
    MvRequest pageRequest = ObjectList::CreateDefaultRequest("PLOT_PAGE");

    // First try to get view from the context
    const char* viewName = GetView(context);

    // Create view request
    if (viewName) {
        // Check if there is a view request
        MvRequest viewRequest = dataReq("_VIEW_REQUEST");
        if (!viewRequest) {
            // Build a default
            viewRequest = ObjectList::UserDefaultRequest(viewName, true);
            viewRequest("_ORIGIN") = "DataBuilder";
        }
        pageRequest("VIEW") = viewRequest;
    }

    defaultSuperPage("PAGES") = pageRequest;

    superpage = new SuperPage(defaultSuperPage);
    ensure(superpage != nullptr);

    // Put the new branch in the tree
    Root::Instance().Insert(superpage);

    // Add the page Ids in the reply
    // Create a Reply
    MvRequest reply;
    superpage->CreateReply(reply);
    context.AddToReply(reply);

    // Drop the data and add draw task if needed
#if 0
if ( !superpage->HasDrawTask () )
  {
      AddTask( *superpage, &Presentable::DrawProlog );
      AddTask( *superpage, &Presentable::Draw );
      superpage->HasDrawTask ( true );
  }
#endif
    superpage->Drop(context);

    return superpage;
}
