#include "QrEncode.h"
#include <CtrlLib/CtrlLib.h>
#include <stdio.h>
#include <qrencode.h>
#include <errno.h>
 

QrEncode::QrEncode()
{
	errorlevel = 3;
	version = 4;
	pixelsize = 4;
	casesensitive = true;
	layer = 0;
	border = 0;
	
	
	
}

Image QrEncode::QrEncode_To_Image(String s1){
	
	is = Size(20+border*2,20+border*2);
	LOG("QrEncode_To_Image:~~1");
    QRcode *qrcode;
    int cs = casesensitive?1:0;
    error = "";
    qrcode = QRcode_encodeString(~s1, version, (QRecLevel) errorlevel, QR_MODE_8, cs);
	
	if ( qrcode == NULL ) {
		
		if ( errno == EINVAL ) {
			error = "Invalid input objectn";
		} else if ( errno == ENOMEM ) {
			error = "Unable to allocate memory for input objects.n";
		} else if ( errno == ERANGE ) {
			error = "Input data is too large.n";
		}
		ImageDraw idr(is);
		return idr;
	} else {
		is = Size(qrcode->width*pixelsize+border*2,qrcode->width*pixelsize+border*2);
		ImageDraw idr(is);
		idr.DrawRect(is,White());
		
		for(int i = 0; i < qrcode->width; i++){
			for(int j = 0; j < qrcode->width; j++){
				uint8_t m = 1<<(layer);
				Color color;
				if (qrcode->data[i+j*qrcode->width]&1){
					color = Black();
					if (layer>0&&qrcode->data[i+j*qrcode->width]&m) color = Color(28, 127, 0);
				} else {
					color = White();
					if (layer>0&&qrcode->data[i+j*qrcode->width]&m) color = Color(166, 255, 162);
				}
				idr.DrawRect((i)*pixelsize+border,j*pixelsize+border,pixelsize,pixelsize,color);
			}
		}
	    QRcode_free(qrcode);
		return idr;
	}
}