package cc.winboll.studio.powerbell;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import androidx.appcompat.widget.Toolbar;
import cc.winboll.studio.libaes.activitys.AboutActivity;
import cc.winboll.studio.libaes.models.APPInfo;
import cc.winboll.studio.libaes.utils.AESThemeUtil;
import cc.winboll.studio.libaes.utils.DevelopUtils;
import cc.winboll.studio.libaes.utils.WinBoLLActivityManager;
import cc.winboll.studio.libaes.views.ADsBannerView;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.activities.BackgroundSettingsActivity;
import cc.winboll.studio.powerbell.activities.BatteryReportActivity;
import cc.winboll.studio.powerbell.activities.ClearRecordActivity;
import cc.winboll.studio.powerbell.activities.SettingsActivity;
import cc.winboll.studio.powerbell.activities.WinBoLLActivity;
import cc.winboll.studio.powerbell.models.BackgroundBean;
import cc.winboll.studio.powerbell.models.ControlCenterServiceBean;
import cc.winboll.studio.powerbell.services.ControlCenterService;
import cc.winboll.studio.powerbell.unittest.MainUnitTest2Activity;
import cc.winboll.studio.powerbell.unittest.MainUnitTestActivity;
import cc.winboll.studio.powerbell.utils.AppConfigUtils;
import cc.winboll.studio.powerbell.utils.BackgroundSourceUtils;
import cc.winboll.studio.powerbell.utils.PermissionUtils;
import cc.winboll.studio.powerbell.utils.ServiceUtils;
import cc.winboll.studio.powerbell.views.MainContentView;

/**
 * 应用核心主活动
 * 功能：管理电池监控、背景设置、服务启停、权限申请等核心功能
 * 适配：Java7 | API30 | 内存泄漏防护 | UI与服务状态实时同步
 */
public class MainActivity extends WinBoLLActivity implements MainContentView.OnViewActionListener {

    // ======================== 静态常量（置顶统一，抽离魔法值）========================
    public static final String TAG = "MainActivity";
    private static final int REQUEST_READ_MEDIA_IMAGES = 1001;
    private static final long DELAY_LOAD_NON_CRITICAL = 500L;
    public static final int MSG_RELOAD_APPCONFIG = 0;
    public static final int MSG_CURRENTVALUEBATTERY = 1;
    public static final int MSG_LOAD_BACKGROUND = 2;
    private static final int MSG_UPDATE_SERVICE_SWITCH = 3;

    // ======================== 静态成员（全局共享，严格管控生命周期）========================
    private static MainActivity sMainActivity;
    private static Handler sGlobalHandler;

    // ======================== 工具类实例（单例，避免重复初始化）========================
    private PermissionUtils mPermissionUtils;
    private AppConfigUtils mAppConfigUtils;
    private BackgroundSourceUtils mBgSourceUtils;

    // ======================== 应用核心实例 =========================
    private App mApplication;
    private MainContentView mMainContentView;
    private ControlCenterServiceBean mServiceControlBean;

    // ======================== 基础视图组件 =========================
    private Toolbar mToolbar;
    private ViewStub mAdsViewStub;
    private ADsBannerView mADsBannerView;
    private Drawable mFrameDrawable;
    private Menu mMenu;

    // ======================== 生命周期方法（按系统调用顺序排列）========================
    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG, "onCreate() | savedInstanceState=" + savedInstanceState);

        initGlobalHandler();
        setContentView(R.layout.activity_main);
        initPermissionUtils();
        initMainContentView();
        initCriticalView();
        initCoreUtilsAsync();
        loadNonCriticalViewDelayed();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        LogUtils.d(TAG, "onPostCreate() | savedInstanceState=" + savedInstanceState);
        mPermissionUtils.startPermissionRequest(this);
        LogUtils.d(TAG, "onPostCreate: 发起权限申请");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d(TAG, "onResume()");
        if (sGlobalHandler != null) {
            sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
            sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
        }
        if (mADsBannerView != null) {
            mADsBannerView.resumeADs(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.d(TAG, "onPause()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy()");

        // 释放广告资源
        if (mADsBannerView != null) {
            mADsBannerView.releaseAdResources();
            mADsBannerView = null;
        }
        // 释放核心视图
        if (mMainContentView != null) {
            mMainContentView.releaseResources();
            mMainContentView = null;
        }
        // 销毁Handler，防止内存泄漏
        if (sGlobalHandler != null) {
            sGlobalHandler.removeCallbacksAndMessages(null);
            sGlobalHandler = null;
        }
        // 释放Drawable
        if (mFrameDrawable != null) {
            mFrameDrawable.setCallback(null);
            mFrameDrawable = null;
        }
        // 置空所有引用
        sMainActivity = null;
        mPermissionUtils = null;
        mAppConfigUtils = null;
        mBgSourceUtils = null;
        mServiceControlBean = null;
        mMenu = null;
        mApplication = null;
        mToolbar = null;
        mAdsViewStub = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d(TAG, "onActivityResult() | requestCode=" + requestCode + " | resultCode=" + resultCode + " | data=" + data);
        mPermissionUtils.handlePermissionRequest(this, requestCode, resultCode, data);
        if (requestCode == REQUEST_READ_MEDIA_IMAGES && sGlobalHandler != null) {
            sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
        }
    }

    // ======================== 菜单与导航方法 ========================
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        LogUtils.d(TAG, "onCreateOptionsMenu() | menu=" + menu);
        mMenu = menu;
        AESThemeUtil.inflateMenu(this, menu);
        if (App.isDebugging()) {
            DevelopUtils.inflateMenu(this, menu);
            getMenuInflater().inflate(R.menu.toolbar_unittest, mMenu);
        }
        getMenuInflater().inflate(R.menu.toolbar_main, mMenu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        LogUtils.d(TAG, "onOptionsItemSelected() | itemId=" + item.getItemId());
        if (AESThemeUtil.onAppThemeItemSelected(this, item)) {
            recreate();
            return true;
        }
        if (DevelopUtils.onDevelopItemSelected(this, item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.action_battery_report:
                startActivity(new Intent(this, BatteryReportActivity.class));
                break;
            case R.id.action_clearrecord:
                startActivity(new Intent(this, ClearRecordActivity.class));
                break;
            case R.id.action_changepicture:
                startActivityForResult(new Intent(this, BackgroundSettingsActivity.class), REQUEST_READ_MEDIA_IMAGES);
                break;
            case R.id.action_unittestactivity:
                startActivity(new Intent(this, MainUnitTestActivity.class));
                break;
			case R.id.action_unittest2activity:
                startActivity(new Intent(this, MainUnitTest2Activity.class));
                break;
            case R.id.action_about:
                startAboutActivity();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public void setupToolbar() {
        super.setupToolbar();
        LogUtils.d(TAG, "setupToolbar()");
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        }
    }

    @Override
    public void onBackPressed() {
        LogUtils.d(TAG, "onBackPressed()");
        moveTaskToBack(true);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        LogUtils.d(TAG, "dispatchKeyEvent() | event=" + event);
        return super.dispatchKeyEvent(event);
    }

    // ======================== 核心初始化方法 ========================
    private void initPermissionUtils() {
        LogUtils.d(TAG, "initPermissionUtils()");
        mPermissionUtils = PermissionUtils.getInstance();
    }

    private void initGlobalHandler() {
        LogUtils.d(TAG, "initGlobalHandler()");
        if (sGlobalHandler == null) {
            sGlobalHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (sMainActivity == null || sMainActivity.isFinishing() || sMainActivity.isDestroyed()) {
                        LogUtils.w(TAG, "handleMessage: Activity已销毁，跳过消息 | what=" + msg.what);
                        return;
                    }
                    LogUtils.d(TAG, "handleMessage() | what=" + msg.what);
                    switch (msg.what) {
                        case MSG_RELOAD_APPCONFIG:
                            sMainActivity.updateViewData();
                            break;
                        case MSG_CURRENTVALUEBATTERY:
                            if (sMainActivity.mMainContentView != null) {
                                sMainActivity.mMainContentView.updateCurrentBattery(msg.arg1);
                                LogUtils.d(TAG, "handleMessage: 更新当前电量 | value=" + msg.arg1);
                            }
                            break;
                        case MSG_LOAD_BACKGROUND:
                            sMainActivity.reloadBackground();
                            sMainActivity.setMainLayoutBackgroundColor();
                            break;
                        case MSG_UPDATE_SERVICE_SWITCH:
                            sMainActivity.updateServiceSwitchUI();
                            break;
                    }
                }
            };
        }
    }

    private void initMainContentView() {
        LogUtils.d(TAG, "initMainContentView()");
        View rootView = findViewById(android.R.id.content);
        mMainContentView = new MainContentView(this, rootView, this);
    }

    private void initCriticalView() {
        LogUtils.d(TAG, "initCriticalView()");
        sMainActivity = this;
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        if (mToolbar != null) {
            mToolbar.setTitleTextAppearance(this, R.style.Toolbar_TitleText);
        }
        mAdsViewStub = findViewById(R.id.stub_ads_banner);
    }

    private void initCoreUtilsAsync() {
        LogUtils.d(TAG, "initCoreUtilsAsync()");
        new Thread(new Runnable() {
				@Override
				public void run() {
					LogUtils.d(TAG, "initCoreUtilsAsync: 异步线程启动 | threadId=" + Thread.currentThread().getId());
					mApplication = (App) getApplication();
					mAppConfigUtils = AppConfigUtils.getInstance(getApplicationContext());
					mBgSourceUtils = BackgroundSourceUtils.getInstance(getActivity());

					// 初始化服务控制配置
					mServiceControlBean = ControlCenterServiceBean.loadBean(getApplicationContext(), ControlCenterServiceBean.class);
					if (mServiceControlBean == null) {
						mServiceControlBean = new ControlCenterServiceBean(false);
						ControlCenterServiceBean.saveBean(getApplicationContext(), mServiceControlBean);
					}

					// 根据配置启停服务
					final boolean isServiceEnable = mServiceControlBean.isEnableService();
					final boolean isServiceAlive = ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName());
					LogUtils.d(TAG, "initCoreUtilsAsync: 服务配置状态 | isServiceEnable=" + isServiceEnable + " | isServiceAlive=" + isServiceAlive);
					if (isServiceEnable && !isServiceAlive) {
						runOnUiThread(new Runnable() {
								@Override
								public void run() {
									ControlCenterService.startControlCenterService(getApplicationContext());
								}
							});
					} else if (!isServiceEnable && isServiceAlive) {
						runOnUiThread(new Runnable() {
								@Override
								public void run() {
									ControlCenterService.stopControlCenterService(getApplicationContext());
								}
							});
					}

					// 主线程更新UI
					runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if (isFinishing() || isDestroyed()) {
									LogUtils.w(TAG, "initCoreUtilsAsync: Activity已销毁，跳过UI更新");
									return;
								}
								// 加载框架背景（适配API23+）
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
									mFrameDrawable = getResources().getDrawable(R.drawable.bg_frame, getTheme());
								} else {
									mFrameDrawable = getResources().getDrawable(R.drawable.bg_frame);
								}
								updateViewData();
								sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
								sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
							}
						});
				}
			}).start();
    }

    private void loadNonCriticalViewDelayed() {
        LogUtils.d(TAG, "loadNonCriticalViewDelayed() | 延迟时长=" + DELAY_LOAD_NON_CRITICAL + "ms");
        new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (isFinishing() || isDestroyed()) {
						LogUtils.w(TAG, "loadNonCriticalViewDelayed: Activity已销毁，跳过广告加载");
						return;
					}
					loadAdsView();
				}
			}, DELAY_LOAD_NON_CRITICAL);
    }

    // ======================== 视图操作方法 ========================
    private void loadAdsView() {
        LogUtils.d(TAG, "loadAdsView()");
        if (mAdsViewStub == null) {
            LogUtils.e(TAG, "loadAdsView: 广告ViewStub为空，加载失败");
            return;
        }
        if (mADsBannerView == null) {
            View adsView = mAdsViewStub.inflate();
            mADsBannerView = adsView.findViewById(R.id.adsbanner);
        }
    }

    private void updateViewData() {
        LogUtils.d(TAG, "updateViewData()");
        if (mMainContentView == null || mFrameDrawable == null) {
            LogUtils.e(TAG, "updateViewData: 核心视图或框架背景为空，更新失败");
            return;
        }
        mMainContentView.updateViewData(mFrameDrawable);
    }

    private void reloadBackground() {
        LogUtils.d(TAG, "reloadBackground()");
        if (mMainContentView == null || mBgSourceUtils == null) {
            LogUtils.e(TAG, "reloadBackground: 核心视图或背景工具类为空，加载失败");
            return;
        }
        BackgroundBean currentBgBean = mBgSourceUtils.getCurrentBackgroundBean();
        if (currentBgBean != null) {
            mMainContentView.backgroundView.loadByBackgroundBean(currentBgBean);
        } else {
            mMainContentView.backgroundView.setBackgroundResource(R.drawable.default_background);
        }
    }

    private void setMainLayoutBackgroundColor() {
        LogUtils.d(TAG, "setMainLayoutBackgroundColor()");
        if (isFinishing() || isDestroyed() || mMainContentView == null || mBgSourceUtils == null) {
            LogUtils.e(TAG, "setMainLayoutBackgroundColor: 上下文无效，设置失败");
            return;
        }
        BackgroundBean currentBgBean = mBgSourceUtils.getCurrentBackgroundBean();
        if (currentBgBean != null) {
            mMainContentView.mainLayout.setBackgroundColor(currentBgBean.getPixelColor());
            LogUtils.d(TAG, "setMainLayoutBackgroundColor: 主布局背景色设置完成 | color=" + currentBgBean.getPixelColor());
        }
    }

    private void updateServiceSwitchUI() {
        LogUtils.d(TAG, "updateServiceSwitchUI()");
        if (mMainContentView == null || mServiceControlBean == null) {
            LogUtils.e(TAG, "updateServiceSwitchUI: 核心视图或服务配置为空，更新失败");
            return;
        }
        boolean configEnabled = mServiceControlBean.isEnableService();
        mMainContentView.setServiceSwitchEnabled(false);
        mMainContentView.setServiceSwitchChecked(configEnabled);
        mMainContentView.setServiceSwitchEnabled(true);
    }

    // ======================== 服务与线程管理方法 ========================
    private void toggleServiceEnableState(boolean isEnable) {
        LogUtils.d(TAG, "toggleServiceEnableState() | 目标状态=" + isEnable);
        if (mServiceControlBean == null) {
            LogUtils.e(TAG, "toggleServiceEnableState: 服务配置为空，切换失败");
            return;
        }
        mServiceControlBean.setIsEnableService(isEnable);
        ControlCenterServiceBean.saveBean(getApplicationContext(), mServiceControlBean);

        // UI开关联动服务启停
        if (isEnable) {
            if (!ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName())) {
                ControlCenterService.startControlCenterService(getApplicationContext());
            }
        } else {
            ControlCenterService.stopControlCenterService(getApplicationContext());
        }

        sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
    }

    // ======================== 页面跳转方法 ========================
    private void startAboutActivity() {
        LogUtils.d(TAG, "startAboutActivity()");
        Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
        APPInfo appInfo = genDefaultAppInfo();
        aboutIntent.putExtra(AboutActivity.EXTRA_APPINFO, appInfo);
        WinBoLLActivityManager.getInstance().startWinBoLLActivity(getApplicationContext(), aboutIntent, AboutActivity.class);
    }

    // ======================== 消息发送方法 ========================
    private void notifyServiceAppConfigChange() {
        LogUtils.d(TAG, "notifyServiceAppConfigChange()");
        ControlCenterService.sendAppConfigStatusUpdateMessage(this);
        reloadAppConfig();
    }

    public static void reloadAppConfig() {
        LogUtils.d(TAG, "reloadAppConfig()");
        if (sGlobalHandler != null) {
            sGlobalHandler.sendEmptyMessage(MSG_RELOAD_APPCONFIG);
        } else {
            LogUtils.w(TAG, "reloadAppConfig: 全局Handler为空，消息发送失败");
        }
    }

    public static void sendCurrentBatteryValueMessage(int value) {
        LogUtils.d(TAG, "sendCurrentBatteryValueMessage() | 电量=" + value);
        if (sGlobalHandler != null) {
            Message msg = sGlobalHandler.obtainMessage(MSG_CURRENTVALUEBATTERY);
            msg.arg1 = value;
            sGlobalHandler.sendMessage(msg);
        } else {
            LogUtils.w(TAG, "sendCurrentBatteryValueMessage: 全局Handler为空，消息发送失败");
        }
    }

    // ======================== 辅助工具方法 ========================
    private APPInfo genDefaultAppInfo() {
        LogUtils.d(TAG, "genDefaultAppInfo()");
        String branchName = "powerbell";
        APPInfo appInfo = new APPInfo();
        appInfo.setAppName(getString(R.string.app_name));
        appInfo.setAppIcon(R.drawable.ic_launcher);
        appInfo.setAppDescription(getString(R.string.app_description));
        appInfo.setAppGitName("WinBoLL");
        appInfo.setAppGitOwner("Studio");
        appInfo.setAppGitAPPBranch(branchName);
        appInfo.setAppGitAPPSubProjectFolder(branchName);
        appInfo.setAppHomePage("https://www.winboll.cc/apks/index.php?project=PowerBell");
        appInfo.setAppAPKName("PowerBell");
        appInfo.setAppAPKFolderName("PowerBell");
        return appInfo;
    }

    // ======================== MainContentView 事件回调 ========================
    @Override
    public void onChargeReminderSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onChargeReminderSwitchChanged() | isChecked=" + isChecked);
        notifyServiceAppConfigChange();
    }

    @Override
    public void onUsageReminderSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onUsageReminderSwitchChanged() | isChecked=" + isChecked);
        notifyServiceAppConfigChange();
    }

    @Override
    public void onServiceSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onServiceSwitchChanged() | isChecked=" + isChecked);
        toggleServiceEnableState(isChecked);
    }

    @Override
    public void onChargeReminderProgressChanged(int progress) {
        LogUtils.d(TAG, "onChargeReminderProgressChanged() | progress=" + progress);
        notifyServiceAppConfigChange();
    }

    @Override
    public void onUsageReminderProgressChanged(int progress) {
        LogUtils.d(TAG, "onUsageReminderProgressChanged() | progress=" + progress);
        notifyServiceAppConfigChange();
    }
}

