package com.qunzhixinxi.hnqz.admin.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.UUID;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeGenerator {

	private static final String QR_CODE_IMAGE_PATH = "/Users/gaoyang/Desktop/"+ UUID.randomUUID() +".png";

	public static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
		if(width==0)
		{
			width=350;
		}

		if(height==0)
		{
			height=350;
		}

		QRCodeWriter qrCodeWriter = new QRCodeWriter();

		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

		bitMatrix=deleteWhite(bitMatrix);

		Path path = FileSystems.getDefault().getPath(filePath);

		MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

	}

	public static BitMatrix deleteWhite(BitMatrix matrix){
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2] + 1;
		int resHeight = rec[3] + 1;


		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for (int i = 0; i < resWidth; i++) {
			for (int j = 0; j < resHeight; j++) {
				if (matrix.get(i + rec[0], j + rec[1]))
					resMatrix.set(i, j);
			}
		}
		return resMatrix;
	}

//	public static void main(String[] args) {
//		try {
//			generateQRCodeImage("This is my first QR Code", 350, 350, QR_CODE_IMAGE_PATH);
//		} catch (WriterException e) {
//			System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
//		} catch (IOException e) {
//			System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
//		}
//
//	}


}
