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 java.io.File;
import java.nio.charset.StandardCharsets;

public class CertActivity extends AppCompatActivity {

    private final static String ACTION_IMP_PUBKEY = "imp_pubkey";
    private final static String ACTION_GEN_KEYS = "gen_keys";
    private final static String ACTION_CERT_REQ = "cert_req";

    private Handler mHandler = 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_IMP_PUBKEY)) {
                String cert = intent.getStringExtra("cert");
                String path = intent.getStringExtra("path");
                int index = intent.getIntExtra("index", 1);

                if (!TextUtils.isEmpty(cert)) {
                    // Import
                    // String cert = intent.getStringExtra("md5");
                    byte[] content = Base64.decode(cert, Base64.DEFAULT);
                    if (content != null) {
                        MicroPhotoService.importPublicKey(index, content);
                    }
                } else if (TextUtils.isEmpty(path)) {
                    String md5 = intent.getStringExtra("md5");
                    File file = new File(path);
                    if (file.exists() && file.isFile()) {
                        MicroPhotoService.importPublicKeyFile(index, path, md5);
                    }
                }
            } else if (TextUtils.equals(action, ACTION_GEN_KEYS)) {
                int index = intent.getIntExtra("index", 0);
                MicroPhotoService.genKeys(index);
            } 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);
            }
        }

        final Activity activity = this;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                activity.finish();
            }
        }, 2000);
    }
}