package com.example.fingerprint_tlk1_uart_demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTabHost;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.rscja.deviceapi.FingerprintWithTLK1NC;
import com.rscja.deviceapi.exception.ConfigurationException;
import com.rscja.utility.StringUtility;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    private FragmentTabHost mTabHost;
    private FragmentManager fm;
    public FingerprintWithTLK1NC mFingerprintWithTLK1NC;
    public ExecutorService mExecutorService = Executors.newCachedThreadPool();
    boolean isPowerOn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        initFingerprint();
        checkReadWritePermission();
    }
    @Override
    protected void onDestroy() {
        if (mFingerprintWithTLK1NC != null) {
            mFingerprintWithTLK1NC.free();
        }
        mProgressDialog.dismiss();
        mExecutorService.shutdownNow();
        super.onDestroy();
    }
    protected void initUI() {
        fm = getSupportFragmentManager();
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, fm, R.id.realtabcontent);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.identification)).setIndicator(getString(R.string.identification)), IdentificationFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.enroll)).setIndicator(getString(R.string.enroll)), CollectionFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.authentication)).setIndicator(getString(R.string.authentication)), AuthenticationFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.template)).setIndicator(getString(R.string.template)), TemplateFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.fingerprintImage)).setIndicator(getString(R.string.fingerprintImage)), ImageFragment.class, null);
    }

    private void checkReadWritePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 0);
                finish();
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }
    ProgressDialog mProgressDialog;
    private void initFingerprint() {
        try {

            mFingerprintWithTLK1NC = FingerprintWithTLK1NC.getInstance();
            new AsyncTask<Void, Integer, Boolean>() {
                @Override
                protected Boolean doInBackground(Void... voids) {
                    isPowerOn = mFingerprintWithTLK1NC.init();
                    return isPowerOn;
                }

                @Override
                protected void onPostExecute(Boolean aBoolean) {
                    mProgressDialog.dismiss();
                    if (aBoolean) {
                        Toast.makeText(MainActivity.this,"init successfully",Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,"init fail",Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                protected void onPreExecute() {
                    mProgressDialog = new ProgressDialog(MainActivity.this);
                    mProgressDialog.setMessage("init...");
                    mProgressDialog.show();
                }
            }.execute();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public boolean checkPageID(String pageIdStr) {
        if (!isPowerOn) {
            showToast(R.string.model_not_power_on);
            return false;
        } else if (TextUtils.isEmpty(pageIdStr)) {
            showToast(R.string.please_input_page_id);
            return false;
        } else if (!StringUtility.isNum(pageIdStr)) {
            showToast(R.string.please_input_number);
            return false;
        }
        return true;
    }
    public void showToast(int text) {
        Toast mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        mToast.show();
    }
    public void showToast(String text) {
        Toast mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        mToast.show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.fingerprinttlk1ncmain, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.clear) {
            if (isPowerOn) {
                boolean r1 = mFingerprintWithTLK1NC.fingerCLEARTemplateBuffer();
                boolean r2 = mFingerprintWithTLK1NC.fingerCLEARTemplate();
                if (r1 && r2) {
                    showToast(R.string.clear_succ);
                } else {
                    showToast(R.string.clear_fail);
                }
            } else {
                showToast("Module is not powered on");
            }
        }
        return super.onOptionsItemSelected(item);
    }
}
