/* AndroidRender.cpp - Render implementation for Android.
* Copyright (C) 2014 Paulo Pinto
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/

#include <algorithm>
#include "Logger.h"
#include "AndroidRender.h"


AndroidRender::AndroidRender(JNIEnv * env, jobject bitmap):env(env), bitmap(bitmap), pixels(nullptr)
{
	int ret;
    if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
    	LogInfo("AndroidBitmap_getInfo() failed ! error=%d");
        return;
    }

    if (info.format != ANDROID_BITMAP_FORMAT_RGB_565) {
    	LogInfo("Bitmap format is not RGB_565 !");
        return;
    }

    if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
    	LogInfo("AndroidBitmap_lockPixels() failed ! error=%d");
        return;
    }
}

AndroidRender::~AndroidRender()
{
	if (pixels != nullptr)
	{
		 AndroidBitmap_unlockPixels(env, bitmap);
	}
}


void AndroidRender::fill_rect(int x, int y, int w, int h, int r, int g, int b)
{
	if (pixels != nullptr)
	{
		int max_y = std::min (y + h, (int)info.height);
		int max_x = std::min (x + w, (int)info.width);

		  void *framebuffer = static_cast<char*>(pixels) + (y * info.stride);
		    for (int yy = y; yy < max_y; yy++) {
		    	uint16_t*  line = static_cast<uint16_t*>(framebuffer);

		        for (int xx = x; xx < max_x; xx++) {

		            line[xx] = toRGB(r,g,b);
		        }

		        // go to next line
		        framebuffer = static_cast<char*>(framebuffer) + info.stride;
		    }


	}
}

void AndroidRender::draw_line(int x0, int y0, int x1, int y1)
{
	fill_rect(x0, y0, x1, y1, 0, 0, 0);
}

int AndroidRender::width()
{
	return info.width;
}

int AndroidRender::height()
{
	return info.height;
}


inline uint16_t  AndroidRender::toRGB(int red, int green, int blue)
{
    return (uint16_t)( (red << 11) | (green << 5) | blue );
}
