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.View;
import android.widget.Switch;
import android.widget.TextView;


import com.dev.devapi.api.SysApi;
import com.xypower.common.HotspotManager;
import com.xypower.common.MicroPhotoContext;
import com.xypower.mpmaster.sms.UpdateSysConfigUtil;

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


public class MainActivity extends AppCompatActivity {

    private static int MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 100;

    private Handler mHandler;

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

        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);

        MicroPhotoContext.AppConfig appConfig = MicroPhotoContext.getMpAppConfig(getApplicationContext());
        ((TextView) findViewById((R.id.cmdid))).setText(TextUtils.isEmpty(appConfig.cmdid) ? "" : appConfig.cmdid);

        findViewById(R.id.btnEnableCam3V3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setCam3V3Enable(true);
            }
        });

        findViewById(R.id.btnDisableCam3V3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setCam3V3Enable(false);
            }
        });

        findViewById(R.id.btnTurnOtgOn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setOtgState(true);
            }
        });

        findViewById(R.id.btnTurnOtgOff).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setOtgState(false);
            }
        });

        findViewById(R.id.nrsec).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setSpiPowerOn(true);
            }
        });

        findViewById(R.id.btnTurnAppOn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // SysApi.enableApp(v.getContext(), "abcd1234");


            }
        });

        findViewById(R.id.btnRestartMpAPP).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MicroPhotoContext.restartMpApp(getApplicationContext());
            }
        });

        /*
        findViewById(R.id.btnTurn485On).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.setRS485Enable(true);
                SysApi.set12VEnable(true);
            }
        });

        findViewById(R.id.btnTurn485Off).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SysApi.set12VEnable(false);
                SysApi.setRS485Enable(false);
            }
        });

        Switch sw = (Switch) findViewById(R.id.btn485ReadMode);
        sw.setChecked(true);
        findViewById(R.id.btn485ReadMode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Switch sw = (Switch) view;
                if (sw.isChecked()) {
                    SysApi.set485ReadMode();
                } else {
                    SysApi.set485WriteMode();
                }
            }
        });

         */

        findViewById(R.id.sendsms).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                boolean gpsEnabled = LocationUtil.isGpsEnabled(MainActivity.this);
//                System.out.printf("g" + gpsEnabled);
//                LocationUtil.register(MainActivity.this, 0, 0, new LocationUtil.OnLocationChangeListener() {
//                    @Override
//                    public void getLastKnownLocation(Location location) {
//                        Log.e("xyh", "onLocationChanged: " + location.getLatitude());
//                    }
//
//                    @Override
//                    public void onLocationChanged(Location location) {
//                        //位置信息变化时触发
//                        Log.e("xyh", "定位方式：" + location.getProvider());
//                        Log.e("xyh", "纬度：" + location.getLatitude());
//                        Log.e("xyh", "经度：" + location.getLongitude());
//                        Log.e("xyh", "海拔：" + location.getAltitude());
//                        Log.e("xyh", "时间：" + location.getTime());
//                        Log.e("xyh", "国家：" + LocationUtil.getCountryName(MainActivity.this, location.getLatitude(), location.getLongitude()));
//                        Log.e("xyh", "获取地理位置：" + LocationUtil.getAddress(MainActivity.this, location.getLatitude(), location.getLongitude()));
//                        Log.e("xyh", "所在地：" + LocationUtil.getLocality(MainActivity.this, location.getLatitude(), location.getLongitude()));
//                        Log.e("xyh", "所在街道：" + LocationUtil.getStreet(MainActivity.this, location.getLatitude(), location.getLongitude()));
//                        LocationUtil.unregister();
//
//                    }
//
//                    @Override
//                    public void onStatusChanged(String provider, int status, Bundle extras) {
//                        System.out.println("dfsad");
//                    }
//                });

//                SysApi.reboot(MainActivity.this);

//                DownloadUtils downloadUtils = new DownloadUtils(getApplicationContext(), "http://180.166.218.222:40101/upgrades/20240509_upd_663c857dbfcf7.apk", "test.apk");

//                    ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
//                    manager.restartPackage(context.getPackageName());
//                String ACTION_UPDATE_CONFIGS = "com.xypower.mpapp.ACT_UPD_CFG";
//                Intent intent = new Intent();
//                intent.setAction(ACTION_UPDATE_CONFIGS);
//                intent.putExtra("restart", 1);
//                // PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//                sendBroadcast(intent);
////                LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
////                localBroadcastManager.sendBroadcast(intent);


//                boolean photoOrVideo;
//                    photoOrVideo = true;
//                List<Long> schedules = new ArrayList<>();
//                long ts = System.currentTimeMillis() / 1000;
//                long val = 0;
//                val |= ((long) 1 << 16);
//                val |= ((long) 255 << 8);
//                val |= photoOrVideo ? 0L : 1L;
//
//                schedules.add(Long.valueOf(val));
//
//                Intent intent1 = new Intent();
//                intent1.setAction(ACTION_TAKE_PHOTO);
//                int cnt = schedules.size();
//                intent1.putExtra(EXTRA_PARAM_SCHEDULES, cnt);
//                for (int idx = 0; idx < cnt; idx++) {
//                    intent1.putExtra(EXTRA_PARAM_SCHEDULE + idx, schedules.get(idx).longValue());
//                }
//                intent1.putExtra(EXTRA_PARAM_TIME, 0);
//                intent1.putExtra(EXTRA_PARAM_TAKING_TIME, ts);
//                sendBroadcast(intent1);


//                UpdateSysConfigUtil.getScheduless(1);
                byte[] bytes = {1, 1, 2, 0, 0, 0, 23, 59};
                String photoSchedules = UpdateSysConfigUtil.getPhotoSchedules(1);

                byte[] decode = Base64.getDecoder().decode(photoSchedules);
                System.out.println(decode);

            }
        });

        /*
        mHandler.postDelayed(new Runnable() {
            public void run() {
                // HotspotManager.enableHotspot(getApplicationContext(), false);
                // SysApi.openHotSpot(getApplicationContext());
            }
        }, 5000);

         */



        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
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back pressed
            return true; // disable it
        }

        return super.onKeyDown(keyCode, event);
    }


}