#pragma once

#include "ZImage.h"
#include "../include/cximage.h"


template < class T > 
void ZImageToCxImage(ZImage<T>& zImg, CxImage& cxImg, T scale=1)
{
	int iWidth = zImg.GetWidth();
	int iHeight = zImg.GetHeight();	
	int iChannel = zImg.GetChannel();

	cxImg.Create(iWidth,iHeight,24);

	if(iChannel==4)
		cxImg.AlphaCreate();

	

	RGBQUAD color;
	for(int j=0;j<iHeight;++j)
		for(int i=0;i<iWidth;++i){
			if(iChannel>=3){
				color.rgbRed = max(0,min(255,zImg.at(i,j,0) * scale));
				color.rgbGreen = max(0,min(255,zImg.at(i,j,1) * scale));
				color.rgbBlue = max(0,min(255,zImg.at(i,j,2) * scale));
				if(iChannel == 4){
					float val = zImg.at(i,j,3);
					color.rgbReserved = min(255,val * scale);
				}
				else
					color.rgbReserved = 255;
			}
			else{
				color.rgbRed = color.rgbGreen = color.rgbBlue = max(0,min(255,zImg.at(i,j,0) * scale));
			}
			cxImg.SetPixelColor(i,iHeight-1-j,color,true);
		}
}

template < class T > 
void CxImageToZImage(CxImage& cxImg, ZImage<T>& zImg, T scale = 1)
{
	int iWidth = cxImg.GetWidth();
	int iHeight = cxImg.GetHeight();	

	int iChannel = 3;

	if(cxImg.AlphaIsValid())
		iChannel = 4;

	zImg.Create(iWidth,iHeight,iChannel);
	
	for(int j=0;j<iHeight;++j)
		for(int i=0;i<iWidth;++i){
			
			RGBQUAD color = cxImg.GetPixelColor(i,iHeight-1-j,true);
			
			zImg.at(i,j,0) = color.rgbRed;

			zImg.at(i,j,1) = color.rgbGreen;

			zImg.at(i,j,2) = color.rgbBlue;			
						
			if(iChannel == 4)
				zImg.at(i,j,3) = color.rgbReserved;
		}
}


template < class A, class B > 
void ZImageToZImage(ZImage<A>& srcImg, ZImage<B>& dstImg)
{
	int iWidth = srcImg.GetWidth();
	int iHeight = srcImg.GetHeight();	
	int iChannel = srcImg.GetChannel();

	dstImg.Create(iWidth,iHeight,iChannel);

	for(int j=0;j<iHeight;++j)
		for(int i=0;i<iWidth;++i){

			for(int c = 0; c<iChannel; ++c){
				dstImg.at(i,j,c) = srcImg.at(i,j,c);
			}

		}
}