package fr.android.pointspermis.captcha;

import android.graphics.Bitmap;
import android.util.Log;

import com.googlecode.tesseract.android.TessBaseAPI;

/**
 * Created by vins on 07/01/15.
 */
public class Captcha {

    public static final String TESSBASE_DIR = "tesseract";
    public static final String DEFAULT_LANGUAGE = "fra";

    private String dataDir;

    public Captcha(String dataDir) {
        this.dataDir = dataDir;
    }

    public String getCode(Bitmap img) {

        String code = null;
        TessBaseAPI baseApi = null;

        try {
            // Attempt to initialize the API.
            baseApi = new TessBaseAPI();

            // Init the API
            baseApi.init(dataDir + "/" + TESSBASE_DIR, DEFAULT_LANGUAGE);
            baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
            baseApi.setImage(img);

            // Get UTF8 decoding
            code = baseApi.getUTF8Text().replace(" ", "");
            //Log.d("DEBUG", "Code: " + code);

            // Attempt to shut down the API.
            baseApi.end();
        } catch (Exception e) {
            Log.e("ERROR", "Error during the captcha recognition process:" + e.getMessage());
        }
        finally {
            // Attempt to shut down the API and return the code.
            try {baseApi.end();}catch(Exception e){}finally{return code;}
        }
    }
}
