package com.xypower.mpmaster;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.xypower.common.MicroPhotoContext;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static int MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 100;

    private Handler mHandler;
    private long mLaunchTime = 0;

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

        mLaunchTime = System.currentTimeMillis();

        // Try to init config
        MpMasterService.initMpMasterConfigurations(getApplicationContext());
        MpMasterService.initMpAppConfigurations(getApplicationContext());

        ActionBar actionBar = getSupportActionBar();

        mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            public void run() {
                requestPermissions();
            }
        }, 100);

        // String buildTime = BuildConfig.BUILD_
        Date date = new Date(BuildConfig.BUILD_TIMESTAMP);
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        actionBar.setTitle(actionBar.getTitle().toString() + " v" + MicroPhotoContext.getVersionName(getApplicationContext()) + " " + sdf.format(date));

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        startMicroPhotoService(getApplicationContext());
    }

    private void requestPermissions() {
        String[] accessPermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.READ_PHONE_STATE,
                /*Manifest.permission.PACKAGE_USAGE_STATS,*/
                /*Manifest.permission.SET_TIME,*/};
        boolean needRequire = false;
        for (String access : accessPermissions) {
            int curPermission = ActivityCompat.checkSelfPermission(MainActivity.this, access);
            if (curPermission != PackageManager.PERMISSION_GRANTED) {
                needRequire = true;
                break;
            }
        }
        if (needRequire) {
            ActivityCompat.requestPermissions(MainActivity.this, accessPermissions, MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE);
            return;
        }
    }

    public static void startMicroPhotoService(Context context) {

        MicroPhotoContext.AppConfig appConfig = MicroPhotoContext.getMpAppConfig(context);

        Intent intent = new Intent(context, MpMasterService.class);
        intent.setAction(MpMasterService.ACTION_START);
        intent.putExtra("cmdid", appConfig.cmdid);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

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

        loadConfigInfo();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back pressed
            return true; // disable it
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //当点击不同的menu item 是执行不同的操作
        switch (id) {
            case R.id.action_dashboard: {
                Intent intent = new Intent(getApplicationContext(), DashboardActivity.class);
                startActivity(intent);
            }
            break;
            case R.id.action_notify_mp_reboot:{
                MicroPhotoContext.restartMpApp(getApplicationContext(), "Manual Restart from MpMst");
            }
            break;

            case R.id.action_reboot_mp: {
                Context context = getApplicationContext();
                Intent intent = context.getPackageManager().getLaunchIntentForPackage(MicroPhotoContext.PACKAGE_NAME_MPAPP);
                int noDelay = 1;
                intent.putExtra("noDelay", noDelay);
                intent.putExtra("reason", "Manual Restart from MpMst");

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                context.startActivity(intent);
            }
            break;
            case R.id.action_reboot_mpmst:{
                MpMasterService.restartApp(getApplicationContext());
            }
            break;
            case R.id.action_refresh:{
                ((TextView) findViewById((R.id.cmdid))).setText("");
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadConfigInfo();
                    }
                }, 500);

            }
            break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadConfigInfo() {
        Context context = getApplicationContext();
        MicroPhotoContext.AppConfig appConfig = MicroPhotoContext.getMpAppConfig(context);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("CMDID：" + (TextUtils.isEmpty(appConfig.cmdid) ? "" : appConfig.cmdid));

        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        stringBuilder.append("\r\n");
        stringBuilder.append("运维主站：" + (TextUtils.isEmpty(masterConfig.server) ? MicroPhotoContext.DEFAULT_MASTER_SERVER : masterConfig.server));
        stringBuilder.append(":");
        stringBuilder.append(Integer.toString((masterConfig.port != 0) ? masterConfig.port : MicroPhotoContext.DEFAULT_MASTER_PORT));
        stringBuilder.append("\r\n");

        stringBuilder.append("心跳模式：");
        if (masterConfig.usingAbsHbTime != 0) {
            stringBuilder.append("固定时间心跳  ");
            if (masterConfig.absHeartbeats != null && masterConfig.absHeartbeats.length > 0) {
                for (int item : masterConfig.absHeartbeats) {
                    stringBuilder.append(MicroPhotoContext.formatHeartbeatTime(item));
                    stringBuilder.append(" ");
                }
            } else {
                stringBuilder.append(MicroPhotoContext.formatHeartbeatTime(MicroPhotoContext.DEFAULT_HEARTBEAT_TIME_FOR_SEPARATE_NW));
            }
        }
        else {
            stringBuilder.append("周期性心跳 / " + masterConfig.heartbeat + "分钟");
        }
        stringBuilder.append("\r\n");

        stringBuilder.append("运维网络：");
        stringBuilder.append(masterConfig.separateNetwork != 0 ? "独立网络" : "公用网络");
        stringBuilder.append("\r\n");
        stringBuilder.append("\r\n");

        stringBuilder.append("启动时间：");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt = new Date(mLaunchTime);
        stringBuilder.append(sdf.format(dt));
        stringBuilder.append("\r\n");

        ((TextView) findViewById((R.id.cmdid))).setText(stringBuilder.toString());
    }

}