/*
 * File Name: image_render_task.cpp
 */

/*
 * This file is part of uds-plugin-images.
 *
 * uds-plugin-images is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * uds-plugin-images is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Copyright (C) 2008 iRex Technologies B.V.
 * All rights reserved.
 */

#include <cassert>
#include <iostream>

#include "image_render_task.h"
#include "log.h"

namespace images
{
    
ImageRenderTask::ImageRenderTask(const std::string & page_anchor,
                                 const ImagePageAttrs & attributes,
                                 int reference_id,
                                 ImagesRenderer *p_renderer,
                                 void * p_user_data)
: anchor(page_anchor)
, ref_id(reference_id)
, renderer(p_renderer)        
, user_data(p_user_data)
{
    LOGPRINTF("anchor[%s], ref_id[%d]", anchor.c_str(), ref_id);

    attrs = attributes;
}

ImageRenderTask::~ImageRenderTask(void)
{
    LOGPRINTF("entry");
}

void ImageRenderTask::execute(void)
{ 
    LOGPRINTF("anchor[%s], zoom[%f], rotation[%d], reference_id[%d]",
               anchor.c_str(), attrs.zoom, attrs.rotation, ref_id );

    assert(renderer);

    // Check wether this page is already in pages_cache?
    ImagePage * ptr = renderer->get_page(anchor, attrs);
    if (ptr)
    {
        WARNPRINTF("Page %s already in pages cache!", anchor.c_str());
        
        // Notify renderer this page is ready now.
        renderer->notify_page_ready(ptr, ref_id, IMG_RENDER_OK, user_data);
        return;
    }

    // Check wether there's enougth memory to render this page?
    ImageRenderStatus ret = renderer->can_render(anchor, attrs);
    if (ret != IMG_RENDER_OK)
    {
        WARNPRINTF("Can't render page %s. Error code: %d", 
                   anchor.c_str(), ret);

        // Notify renderer this page is not ready for some reason.
        renderer->notify_page_ready(0, ref_id, ret, user_data);
        return;
    }
    
    // Get the anchor of the page_num
    LOGPRINTF("%s", anchor.c_str());
    
    // Render the image
    ImagePage * image = new ImagePage(anchor, attrs); 
    assert(image);
    image->render();
    
    // Push the ImagePage into 'pages cache'
    renderer->add_page(image);
        
    // Notify renderer this page is ready.
    renderer->notify_page_ready(image, ref_id, ret, user_data);
}
};


