package com.xypower.mpapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.xypower.common.FilesUtils;
import com.xypower.common.JSONUtils;
import com.xypower.common.MicroPhotoContext;
import com.xypower.mpapp.v2.Camera2VideoActivity;

import org.json.JSONObject;

import java.io.File;


public class BridgeActivity extends AppCompatActivity {

    private final static String TAG = "MPLOG";

    private final static String ACTION_IMP_PUBKEY = "imp_pubkey";
    private final static String ACTION_IMP_PRIKEY = "imp_prikey";
    private final static String ACTION_GEN_KEYS = "gen_keys";
    private final static String ACTION_CERT_REQ = "cert_req";
    private final static String ACTION_BATTERY_VOLTAGE = "query_bv";
    private final static String ACTION_RECORDING = "recording";
    private final static String ACTION_TAKE_PHOTO = "take_photo";
    private final static String ACTION_QUERY_SEC_VERSION = "query_sec_v";

    private final static int REQUEST_CODE_RECORDING = Camera2VideoActivity.REQUEST_CODE_RECORDING;

    private Handler mHandler = null;
    private boolean m3V3TurnedOn = false;
    private boolean mAutoClose = true;

    private String mVideoFilePath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cert);

        mHandler = new Handler();

        Intent intent = getIntent();
        final String action = intent.getStringExtra("action");
        if (!TextUtils.isEmpty(action)) {
            if (TextUtils.equals(action, ACTION_QUERY_SEC_VERSION)) {
                String resultFile = intent.getStringExtra("resultFile");
                String version = MicroPhotoService.querySecVersion();

                if (!TextUtils.isEmpty(resultFile)) {
                    FilesUtils.ensureParentDirectoryExisted(resultFile);
                    FilesUtils.writeTextFile(resultFile, version);
                }
            } else if (TextUtils.equals(action, ACTION_IMP_PUBKEY)) {
                String cert = intent.getStringExtra("cert");
                String path = intent.getStringExtra("path");
                String resultFile = intent.getStringExtra("resultFile");
                int index = intent.getIntExtra("index", 0);

                boolean res = false;
                if (!TextUtils.isEmpty(cert)) {
                    // Import
                    // String cert = intent.getStringExtra("md5");
                    byte[] content = Base64.decode(cert, Base64.DEFAULT);
                    if (content != null) {
                        res = MicroPhotoService.importPublicKey(index, content);
                    }
                } else if (TextUtils.isEmpty(path)) {
                    String md5 = intent.getStringExtra("md5");
                    File file = new File(path);
                    if (file.exists() && file.isFile()) {
                        res = MicroPhotoService.importPublicKeyFile(index, path, md5);
                    }
                }

                if (!TextUtils.isEmpty(resultFile)) {
                    FilesUtils.ensureParentDirectoryExisted(resultFile);
                    FilesUtils.writeTextFile(resultFile, res ? "1" : "0");
                }
            } else if (TextUtils.equals(action, ACTION_IMP_PRIKEY)) {
                String cert = intent.getStringExtra("cert");
                String path = intent.getStringExtra("path");
                String resultFile = intent.getStringExtra("resultFile");
                int index = intent.getIntExtra("index", 0);

                boolean res = false;
                if (!TextUtils.isEmpty(cert)) {
                    // Import
                    byte[] content = Base64.decode(cert, Base64.DEFAULT);
                    if (content != null) {
                        res = MicroPhotoService.importPrivateKey(index, content);
                    }
                } else if (TextUtils.isEmpty(path)) {
                    String md5 = intent.getStringExtra("md5");
                    File file = new File(path);
                    if (file.exists() && file.isFile()) {
                        res = MicroPhotoService.importPrivateKeyFile(index, path, md5);
                    }
                }

                Log.i(TAG, "Import Private Key result=" + (res ? "1" : "0"));

                if (!TextUtils.isEmpty(resultFile)) {
                    FilesUtils.ensureParentDirectoryExisted(resultFile);
                    FilesUtils.writeTextFile(resultFile, res ? "1" : "0");
                }

            } else if (TextUtils.equals(action, ACTION_GEN_KEYS)) {
                int index = intent.getIntExtra("index", 0);
                boolean res = MicroPhotoService.genKeys(index);
                String path = intent.getStringExtra("path");
                if (!TextUtils.isEmpty(path)) {
                    FilesUtils.ensureParentDirectoryExisted(path);
                    FilesUtils.writeTextFile(path, res ? "1" : "0");
                }
            } else if (TextUtils.equals(action, ACTION_CERT_REQ)) {
                int index = intent.getIntExtra("index", 0);
                int type = intent.getIntExtra("type", 0);
                String subject = intent.getStringExtra("subject");
                String path = intent.getStringExtra("path");
                MicroPhotoService.genCertRequest(index, type, subject, path);
            } else if (TextUtils.equals(action, ACTION_BATTERY_VOLTAGE)) {
                String path = intent.getStringExtra("path");
                // #define CMD_GET_CHARGING_BUS_VOLTAGE_STATE      112
                // #define CMD_GET_BAT_VOL_STATE                   115
                // #define CMD_GET_BAT_BUS_VOLTAGE_STATE           117
                int bv = MicroPhotoService.getGpioInt(117);
                int bcv = MicroPhotoService.getGpioInt(112);
                if (!TextUtils.isEmpty(path)) {
                    FilesUtils.ensureParentDirectoryExisted(path);
                    FilesUtils.writeTextFile(path + ".tmp", Integer.toString(bv) + " " + Integer.toString(bcv));
                    File file = new File(path + ".tmp");
                    file.renameTo(new File(path));
                }
            } else if (TextUtils.equals(action, ACTION_TAKE_PHOTO)) {
                String path = intent.getStringExtra("path");
                int channel = intent.getIntExtra("channel", 1);
                int preset = intent.getIntExtra("preset", 0xFF);

                int width = intent.getIntExtra("width", 0);
                int height = intent.getIntExtra("height", 0);

                String leftTopOsd = intent.getStringExtra("leftTopOsd");
                String rightTopOsd = intent.getStringExtra("rightTopOsd");
                String rightBottomOsd = intent.getStringExtra("rightBottomOsd");
                String leftBottomOsd = intent.getStringExtra("leftBottomOsd");

                String appPath = MicroPhotoContext.buildMpAppDir(getApplicationContext());
                File configFile = new File(appPath);
                configFile = new File(configFile, "data/channels/" + Integer.toString(channel) + ".json");

                File tmpConfigFile = new File(appPath);
                tmpConfigFile = new File(tmpConfigFile, "tmp/" + Integer.toString(channel) + "-" + Long.toString(System.currentTimeMillis()) + ".json");

                if (configFile.exists()) {
                    try {

                        FilesUtils.copyFile(configFile, tmpConfigFile);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                JSONObject configJson = JSONUtils.loadJson(tmpConfigFile.getAbsolutePath());
                try {
                    if (configJson == null) {
                        configJson = new JSONObject();
                    }
                    if (width > 0) {
                        configJson.put("resolutionCX", width);
                    }
                    if (height > 0) {
                        configJson.put("resolutionCY", height);
                    }

                    JSONObject osdJson = configJson.getJSONObject("osd");
                    if (osdJson == null) {
                        osdJson = configJson.put("osd", new JSONObject());
                    }
                    osdJson.put("leftTop", TextUtils.isEmpty(leftTopOsd) ? "" : leftTopOsd);
                    osdJson.put("rightTop", TextUtils.isEmpty(rightTopOsd) ? "" : rightTopOsd);
                    osdJson.put("rightBottom", TextUtils.isEmpty(rightBottomOsd) ? "" : rightBottomOsd);
                    osdJson.put("leftBottom", TextUtils.isEmpty(leftBottomOsd) ? "" : leftBottomOsd);

                    JSONUtils.saveJson(tmpConfigFile.getAbsolutePath(), configJson);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                } else {
                    FilesUtils.ensureParentDirectoryExisted(path);
                }

                MicroPhotoService.takePhoto(channel, preset, true, tmpConfigFile.getAbsolutePath(), path);
                if (tmpConfigFile.exists()) {
                    tmpConfigFile.delete();
                }

            }  else if (TextUtils.equals(action, ACTION_RECORDING)) {
                String path = intent.getStringExtra("path");
                int channel = intent.getIntExtra("channel", 1);
                int cameraId = intent.getIntExtra("cameraId", -1);
                int quality = intent.getIntExtra("quality", 0);
                int width = intent.getIntExtra("width", 1280);
                int height = intent.getIntExtra("height", 720);
                int duration = intent.getIntExtra("duration", 15);
                int orientation = intent.getIntExtra("orientation", 0);
                long videoId = System.currentTimeMillis() / 1000;

                String leftTopOsd = intent.getStringExtra("leftTopOsd");
                String rightTopOsd = intent.getStringExtra("rightTopOsd");
                String rightBottomOsd = intent.getStringExtra("rightBottomOsd");
                String leftBottomOsd = intent.getStringExtra("leftBottomOsd");

                if (cameraId == -1) {
                    cameraId = channel - 1;
                }

                Intent recordingIntent = MicroPhotoService.makeRecordingIntent(getApplicationContext(),
                        false, cameraId, videoId, duration, width, height, quality, orientation,
                        leftTopOsd, rightTopOsd, rightBottomOsd, leftBottomOsd, null);

                mVideoFilePath = path;
                mAutoClose = false;

                recordingIntent.putExtra("resultType", 1);
                startActivityForResult(recordingIntent, REQUEST_CODE_RECORDING);
            }
        }

        if (mAutoClose) {
            final Activity activity = this;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "BridgeActivity will finish automatically");
                    activity.finish();
                }
            }, 2000);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (m3V3TurnedOn) {
            MicroPhotoService.setCam3V3Enable(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_RECORDING) {
            if (mVideoFilePath != null && data != null) {
                String path = data.getStringExtra("path");
                if (path != null) {
                    File file = new File(path);
                    file.renameTo(new File(mVideoFilePath));
                }
            }
            this.finish();
        }
    }

}