package com.example.fingerprint_tlk1_uart_demo;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.os.Environment;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.rscja.utility.StringUtility;

import cn.qqtheme.framework.picker.FilePicker;
import cn.qqtheme.framework.util.StorageUtils;


public class TemplateFragment extends Fragment  implements View.OnClickListener {
    private String TAG = "TemplateFragment";

    private MainActivity mActivity;
    private EditText etPageId, etData, etPageIdDownload;
    private Button btnUpload, btnDownload, btnSelect;
    private TextView tvMsgUpload, tvMsgDownload;

    private int pageID;
    private String fingerprintDataPath = "sdcard/fingerprint.txt";

    private static final int UPLOAD_SUCC = 1;
    private static final int UPLOAD_FAIL = -1;
    private static final int DOWNLOAD_SUCC = 2;
    private static final int DOWNLOAD_FAIL = -2;

    boolean isRuing=false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mActivity.mProgressDialog.dismiss();
            switch (msg.what) {
                case UPLOAD_FAIL:
                    tvMsgUpload.setText("Upload failure");
                    tvMsgUpload.setTextColor(ActivityCompat.getColor(getContext(), R.color.colorAccent));
                    showToast("Upload failure");
                    break;
                case UPLOAD_SUCC:
                    tvMsgUpload.setText("Upload successfully\nsave:" + fingerprintDataPath);
                    tvMsgUpload.setTextColor(ActivityCompat.getColor(getContext(), R.color.green_0C7910));
                    showToast("Upload successfully");
                    break;
                case DOWNLOAD_FAIL:
                    tvMsgDownload.setText("Download failure");
                    tvMsgDownload.setTextColor(ActivityCompat.getColor(getContext(), R.color.colorAccent));
                    showToast("Download failure");
                    break;
                case DOWNLOAD_SUCC:
                    tvMsgDownload.setText("Download successfully");
                    tvMsgDownload.setTextColor(ActivityCompat.getColor(getContext(), R.color.green_0C7910));
                    showToast("Download successfully");
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_template, container, false);
        init(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = (MainActivity) getActivity();
    }

    @Override
    public void onDestroyView() {
        Log.e(TAG, "onDestroyView");
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroyView();
    }

    private void init(View view) {
        etPageId = view.findViewById(R.id.etPageId);
        etData = view.findViewById(R.id.etData);
        etPageIdDownload = view.findViewById(R.id.etPageIdDownload);
        tvMsgUpload = view.findViewById(R.id.tvMsgUpload);
        tvMsgDownload = view.findViewById(R.id.tvMsgDownload);
        btnUpload = view.findViewById(R.id.btnUpload);
        btnUpload.setOnClickListener(this);
        btnDownload = view.findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(this);
        btnSelect = view.findViewById(R.id.btnSelect);
        btnSelect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnUpload:
                upload();
                break;
            case R.id.btnDownload:
                download();
                break;
            case R.id.btnSelect:
//                if(!mActivity.requestPermission()) {
//                    return;
//                }
                onFilePicker(v);
                break;
        }
    }

    private void upload() {
        String pageIdStr = etPageId.getText().toString();
        if(!mActivity.checkPageID(pageIdStr)) {
            return;
        }

        pageID = StringUtility.string2Int(pageIdStr, -1);
        if (pageID < 0 || pageID > 127) {
            showToast("Page ID is error, from 0 to 127");
            return;
        }

        mActivity.mProgressDialog.setMessage("Uploading...");
        mActivity.mProgressDialog.show();
        mActivity.mProgressDialog.setCancelable(false);
        isRuing=true;
        mActivity.mExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                while (isRuing) {
                    if (mActivity.mFingerprintWithTLK1NC.fingerGETImage() > 0) {
                        if (mActivity.mFingerprintWithTLK1NC.fingerStoreCharToFlashPage(pageID)) {
                            byte[] bytes = mActivity.mFingerprintWithTLK1NC.fingerUPTemplateFromFlashPage(pageID);
                            if (bytes != null && bytes.length > 0) {
                                String data = StringUtility.bytesHexString(bytes, bytes.length);
                                FileUtils.writeFile(fingerprintDataPath, data, false);
                                mHandler.sendEmptyMessage(UPLOAD_SUCC);
                            } else {
                                mHandler.sendEmptyMessage(UPLOAD_FAIL);
                            }
                        }else{
                            mHandler.sendEmptyMessage(UPLOAD_FAIL);
                        }

                        isRuing=false;
                        return;
                    }
                }
            }
        });
    }

    private void download() {
        final String dataPath = etData.getText().toString();
        if(TextUtils.isEmpty(dataPath)) {
            showToast("Please select a fingerprint data file first");
            return;
        }

        String pageIdStr = etPageIdDownload.getText().toString();
        if(!mActivity.checkPageID(pageIdStr)) {
            return;
        }

        pageID = StringUtility.string2Int(pageIdStr, -1);
        if (pageID < 0 || pageID > 127) {
            showToast("Page ID is error, from 0 to 127");
            return;
        }

        mActivity.mProgressDialog.setMessage("Downloading...");
        mActivity.mProgressDialog.show();
        mActivity.mExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String data = FileUtils.readFile(dataPath);
                    byte[] bytes = StringUtility.hexString2Bytes(data);
                    Log.e(TAG, "data bytes.length=" + bytes.length);
                    if (mActivity.mFingerprintWithTLK1NC.fingerDOWNTemplateToFlashPage(pageID, bytes)) {
                        mHandler.sendEmptyMessage(DOWNLOAD_SUCC);
                    } else {
                        mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "fingerDOWNTemplateToFlashPage error:" + e.getMessage());
                    mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                }
            }
        });

    }

    public void onFilePicker(View view) {
        FilePicker picker = new FilePicker(mActivity, FilePicker.FILE);
        picker.setRootPath(Environment.getExternalStorageDirectory().getAbsolutePath());
        picker.setShowHideDir(false);
//        picker.setAllowExtensions(new String[]{".txt"});
        picker.setFileIcon(getResources().getDrawable(R.drawable.lfile_file_style_blue));
        picker.setFolderIcon(getResources().getDrawable(R.drawable.lfile_folder_style_blue));
        picker.setOnFilePickListener(new FilePicker.OnFilePickListener() {
            @Override
            public void onFilePicked(String currentPath) {
                etData.setText(currentPath);
            }
        });
        picker.show();
    }

    public void onDirPicker(View view) {
        FilePicker picker = new FilePicker(mActivity, FilePicker.DIRECTORY);
        picker.setRootPath(StorageUtils.getExternalRootPath() + "Download/");
        picker.setItemHeight(30);
        picker.setOnFilePickListener(new FilePicker.OnFilePickListener() {
            @Override
            public void onFilePicked(String currentPath) {
                showToast(currentPath);
            }
        });
        picker.show();
    }
    public void showToast(String text) {
        Toast mToast = Toast.makeText(getContext(), text, Toast.LENGTH_SHORT);
        mToast.show();
    }
}
