package com.example.fingerprint_tlk1_uart_demo;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;

import com.mx.finger.alg.MxISOFingerAlg;
import com.mx.finger.api.msc.MxIsoMscFingerApiFactory;
import com.mx.finger.common.MxImage;
import com.mx.finger.utils.RawBitmapUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Wsq {

    private MxISOFingerAlg mxFingerAlg;

    public Wsq(Context context){
        MxIsoMscFingerApiFactory fingerFactory = new MxIsoMscFingerApiFactory(context);
        mxFingerAlg = fingerFactory.getAlg();
    }
    public byte[] decompressWSQ(String wsqImgPath) {
        byte[] wsqBuffer = loadFile(wsqImgPath);
        if (wsqBuffer == null) {
            return null;
        }
        byte[] imageBuffer = new byte[256 * 360];
        int[] width = new int[1];
        int[] height = new int[1];
        int[] dpi = new int[1];
        long result = mxFingerAlg.decompressWSQ(wsqBuffer, wsqBuffer.length, imageBuffer, width, height, dpi);
        if (result == 0) {
            return imageBuffer;
        }
           return null;
    }

    public boolean compressWSQ(byte[] raw,String wsqImgPath) {
         if(raw==null || raw.length==0)
             return false;

        int width=256;
        int height=360;
        byte[] wsq = new byte[width * height];
        int[] wsqLen = new int[1];
        long result = mxFingerAlg.compressWSQ(raw,width,height, 500, 10, wsq, wsqLen);
        if (result == 0) {
          return saveFile(wsqImgPath, wsq, wsqLen[0]);
        } else {
          return false;
        }
    }
    private boolean saveFile(String filename, byte[] buffer, int len) {
        try {
            File file = new File(filename);
            FileOutputStream out = new FileOutputStream(file);
            out.write(buffer, 0, len);
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    private byte[] loadFile(String filename) {
        File file = new File(filename);
        try {
            FileInputStream out = new FileInputStream(file);
            int available = out.available();
            byte[] buffer = new byte[available];
            int ret = out.read(buffer);
            out.close();
            if (ret != available) {
                return null;
            }
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
