package com.yztiot.streetlamp;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yztiot.demo.yztiotManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Handler handler = new Handler();
    private ImageView lightModeImage,lowerLamplight,upperLamplight;
    private ImageButton btnSettings,btnSpeed,btnTiming;
    private Button btnSend,loginPhoto,btnLogin;
    private LightModeAdapter lightModeAdapter;
    private Spinner spinner;
    private boolean isSerialOpen = false;
    private int upperLight = 01, upperColor = -1;
    private int lowerLight = 02, lowerColor = -1;
    public static final String PREFS_NAME = "password_prefs";
    private static final String SUPER_ADMIN_PASSWORD_KEY = "super_admin_password";
    private static final String USER_PASSWORD_KEY = "user_password";
    private String superAdminPassword = "654321";
    private int saveSwitch;
    private String frame;
    private String userPassword = "000000";
    public static final String START_HOUR_KEY = "start_hour";
    public static final String START_MINUTE_KEY = "start_minute";
    public static final String END_HOUR_KEY = "end_hour";
    public static final String SWITCH_KEY = "switch";
    public static final String FRAME_KEY = "frame";
    public static final String END_MINUTE_KEY = "end_minute";
    private View loginInputLayout;
    private EditText loginInput;
    private FrameLayout screenLayout;
    private boolean isLoginInputVisible = false;
    private RecyclerView lightModeContainer,colorModeContainer;
    private int selectedLightModeUpper;
    private int selectedLightModeLower;
    public static com.yztiot.demo.yztiotManager yztiotManager = new yztiotManager();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        yztiotManager.setContext(this);
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        yztiotManager.setBootPackageActivity("com.yztiot.streetlamp","com.yztiot.streetlamp.MainActivity");
        findId();
        layout();
        onClickListener();
        openSerial();
        initializePasswords();
        loadPasswords();
        if (saveSwitch == 0){
            cancelAlarmManager();
        } else if (saveSwitch == 1){
            setAlarmManager();
        }
        initializeSelection();
    }
 private void initializeSelection() {
     int lightModePosition = Integer.parseInt(frame.substring(6, 8), 16); // 子节目1
     int colorModePosition = Integer.parseInt(frame.substring(10, 12), 16); // 子节目2

     // 设置 lightModeContainer 的选中位置
     if (colorModeContainer.getAdapter() != null) {
         LightModeAdapter lightModeAdapter = (LightModeAdapter) lightModeContainer.getAdapter();
         lightModeAdapter.setSelectedPosition(lightModePosition );
         lightModeAdapter.notifyDataSetChanged();
     }

     // 设置 colorModeContainer 的选中位置
     if (colorModeContainer.getAdapter() != null) {
         LightModeAdapter colorModeAdapter = (LightModeAdapter) colorModeContainer.getAdapter();
         colorModeAdapter.setSelectedPosition(colorModePosition); // 索引从0开始
         colorModeAdapter.notifyDataSetChanged();
     }

     Log.d("lightModeAdapter", "lightModeAdapter: " + lightModeAdapter + " colorModeContainer :" + colorModeContainer);
    }
    private void onClickListener(){

        btnSend.setOnClickListener(v -> {
            SerialManage.getInstance().init(new SerialInter() {
                @Override
                public void connectMsg(String path, boolean isSucc) {
                    Log.d("SerialManage", "串口连接成功");
                }

                @Override
                public void readData(String path, byte[] bytes, int size) {
                    String receivedText = new String(bytes, 0, size);
                }
            });

            if (!isSerialOpen) {
                Toast.makeText(this, R.string.port_not_open, Toast.LENGTH_SHORT).show();
                return;
            }
            String frame = buildFrame();
            sendDate(frame);
            Toast.makeText(this, R.string.send_successfully, Toast.LENGTH_SHORT).show();
        });

        btnTiming.setOnLongClickListener(v -> {
            new AlertDialog.Builder(MainActivity.this, R.style.BlueAlertDialog)
                    .setTitle(R.string.timer_switch)
                    .setMessage(R.string.confirm_open_timer) // 提示信息

                    .setNegativeButton(R.string.cancel, (dialog, which) -> {
                        setAlarmManager();
                        Toast.makeText(MainActivity.this, R.string.timer_cancelled, Toast.LENGTH_SHORT).show();
                    })
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        // 用户确认打开定时开关
                        Toast.makeText(MainActivity.this, R.string.timer_opened, Toast.LENGTH_SHORT).show();
                        // 例如，设置定时器
                        cancelAlarmManager();
                    })
                    .show();

            return true; // 返回 true 表示事件已处理
        });
        btnTiming.setOnClickListener(v -> {
            final Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);

            // 弹出开始时间选择对话框
            TimePickerDialog startTimePickerDialog = new TimePickerDialog(
                    MainActivity.this,
                    R.style.BlueAlertDialog,
                    (timePicker, selectedHour, selectedMinute) -> {
                        saveTime(START_HOUR_KEY, selectedHour);
                        saveTime(START_MINUTE_KEY, selectedMinute);
                        TimePickerDialog endTimePickerDialog = new TimePickerDialog(
                                MainActivity.this,
                                R.style.BlueAlertDialog,
                                (timePicker1, selectedHour1, selectedMinute1) -> {
                                    saveTime(END_HOUR_KEY, selectedHour1);
                                    saveTime(END_MINUTE_KEY, selectedMinute1);
                                    setAlarmManager();
                                    Log.d("TimePicker", "开始时间: " + selectedHour + ":" + selectedMinute);
                                    Log.d("TimePicker", "结束时间: " + selectedHour1 + ":" + selectedMinute1);
                                },
                                hour, minute, true
                        );
                        Toast.makeText(this, R.string.select_end_time, Toast.LENGTH_SHORT).show();
                        endTimePickerDialog.show();
                    },
                    hour, minute, true
            );

            Toast.makeText(this, R.string.select_start_time, Toast.LENGTH_SHORT).show();
            startTimePickerDialog.show();
        });

        btnSpeed.setOnClickListener(v -> {
            // 创建 SeekBar
            SeekBar seekBar = new SeekBar(this);
            seekBar.setMax(100);
            seekBar.setProgress(50);

            // 包装为带 padding 的布局
            LinearLayout layout = new LinearLayout(this);
            layout.setPadding(50, 40, 50, 10);
            layout.addView(seekBar);

            // 创建对话框
            new AlertDialog.Builder(this, R.style.BlueAlertDialog)
                    .setTitle(R.string.speed)
                    .setView(layout)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        int speedValue = seekBar.getProgress();
                        Log.d("SpeedDialog", "设置速度为: " + speedValue);
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        });

        btnSettings.setOnClickListener(v -> {
            // 第一步：弹出输入超级管理员密码的对话框
            EditText adminInput = new EditText(this);
            adminInput.setHint(R.string.enter_su_password);
            adminInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

            LinearLayout adminLayout = new LinearLayout(this);
            adminLayout.setPadding(50, 40, 50, 10);
            adminLayout.addView(adminInput);

            new AlertDialog.Builder(this, R.style.BlueAlertDialog)
                    .setTitle(R.string.authentication)
                    .setView(adminLayout)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        String enteredPassword = adminInput.getText().toString();
                        if (enteredPassword.equals(superAdminPassword)) {
                            // 验证成功，弹出修改用户密码对话框
                            EditText newPasswordInput = new EditText(this);
                            newPasswordInput.setHint(R.string.enter_new_password);
                            newPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

                            LinearLayout newPasswordLayout = new LinearLayout(this);
                            newPasswordLayout.setPadding(50, 40, 50, 10);
                            newPasswordLayout.addView(newPasswordInput);

                            new AlertDialog.Builder(this, R.style.BlueAlertDialog)
                                    .setTitle(R.string.modify_password)
                                    .setView(newPasswordLayout)
                                    .setPositiveButton(R.string.confirm, (dialog2, which2) -> {
                                        String newPassword = newPasswordInput.getText().toString();
                                        if (!newPassword.isEmpty()) {
                                            userPassword = newPassword;
                                            savePasswords();
                                            Toast.makeText(MainActivity.this, R.string.password_modified_successfully + userPassword, Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(MainActivity.this, R.string.password_cannot_be_empty, Toast.LENGTH_SHORT).show();
                                        }
                                    })
                                    .setNegativeButton(R.string.cancel, null)
                                    .show();
                        } else {
                            Toast.makeText(MainActivity.this, R.string.wrong_password, Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        });
        loginPhoto.setOnClickListener(v -> {
            isLoginInputVisible = !isLoginInputVisible;
            loginInputLayout.setVisibility(isLoginInputVisible ? View.VISIBLE : View.GONE);
        });
        btnLogin.setOnClickListener(v -> {
            String inputPassword = loginInput.getText().toString().trim();
            Log.d("LoginInput", "输入的密码: " + inputPassword);
            Log.d("LoginInput", "superAdminPassword: " + superAdminPassword+"userPassword: " + userPassword);

            if (inputPassword.equals(superAdminPassword) || inputPassword.equals(userPassword)) {
                Toast.makeText(this, R.string.login_successfully, Toast.LENGTH_SHORT).show();
                screenLayout.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, R.string.wrong_password, Toast.LENGTH_SHORT).show();
            }
            loginInput.setText("");
        });

    }
    private void cancelAlarmManager() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent startIntent = new Intent(this, TimingReceiver.class);
        startIntent.setAction("com.yztiot.streetlamp.START_ALARM");
        PendingIntent startPendingIntent = PendingIntent.getBroadcast(this, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent endIntent = new Intent(this, TimingReceiver.class);
        endIntent.setAction("com.yztiot.streetlamp.END_ALARM");
        PendingIntent endPendingIntent = PendingIntent.getBroadcast(this, 1, endIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (alarmManager != null) {
            alarmManager.cancel(startPendingIntent);
            alarmManager.cancel(endPendingIntent);
            Log.d("MainActivity", "Alarms canceled");
        }

        // 更换按钮背景图
        btnTiming.setBackgroundResource(R.drawable.btn_timing_off);
        saveSwitch(SWITCH_KEY,0);
    }
    private void setAlarmManager() {
        // 获取保存的时间
        SharedPreferences prefs = getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
        int startHour = prefs.getInt(MainActivity.START_HOUR_KEY, -1);
        int startMinute = prefs.getInt(MainActivity.START_MINUTE_KEY, -1);
        int endHour = prefs.getInt(MainActivity.END_HOUR_KEY, -1);
        int endMinute = prefs.getInt(MainActivity.END_MINUTE_KEY, -1);

        if (startHour != -1 && startMinute != -1 && endHour != -1 && endMinute != -1) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            // 设置开始时间
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.set(Calendar.HOUR_OF_DAY, startHour);
            startCalendar.set(Calendar.MINUTE, startMinute);
            startCalendar.set(Calendar.SECOND, 0);

            if (startCalendar.getTimeInMillis() < System.currentTimeMillis()) {
                startCalendar.add(Calendar.DAY_OF_YEAR, 1);
            }

            Intent startIntent = new Intent(this, TimingReceiver.class);
            startIntent.setAction("com.yztiot.streetlamp.START_ALARM");
            PendingIntent startPendingIntent = PendingIntent.getBroadcast(this, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), startPendingIntent);
            Log.d("MainActivity", "Start alarm set for: " + startCalendar.getTime());

            // 设置结束时间
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.set(Calendar.HOUR_OF_DAY, endHour);
            endCalendar.set(Calendar.MINUTE, endMinute);
            endCalendar.set(Calendar.SECOND, 0);

            if (endCalendar.getTimeInMillis() < System.currentTimeMillis()) {
                endCalendar.add(Calendar.DAY_OF_YEAR, 1);
            }

            Intent endIntent = new Intent(this, TimingReceiver.class);
            endIntent.setAction("com.yztiot.streetlamp.END_ALARM");
            PendingIntent endPendingIntent = PendingIntent.getBroadcast(this, 1, endIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endCalendar.getTimeInMillis(), endPendingIntent);
            Log.d("MainActivity", "End alarm set for: " + endCalendar.getTime());
            btnTiming.setBackgroundResource(R.drawable.btn_timing_on);
            saveSwitch(SWITCH_KEY,1);
        } else {
            Log.d("MainActivity", "No valid time settings found");
        }
    }
    private void saveSwitch(String key, int value) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.apply();
        Log.d("SwitchSave", key + ": " + value);
    }
    private void saveTime(String key, int value) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.apply();
        Log.d("TimeSave", key + ": " + value);
    }
    private void saveFrame(String key, String value) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();
        Log.d("saveFrame", key + ": " + value);
    }
    private void savePasswords() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(SUPER_ADMIN_PASSWORD_KEY, superAdminPassword);
        editor.putString(USER_PASSWORD_KEY, userPassword);
        editor.apply();
        Log.d("PasswordSave", "Passwords saved successfully");
    }
    private String buildFrame() {
        byte FH = 0x55;
        byte channel = (byte) (spinner.getSelectedItemPosition() + 1);

        byte upperHigh = (byte) ((upperLight ) & 0xFF);
        byte upperLow  = (byte) (upperColor & 0xFF);
        byte lowerHigh = (byte) ((lowerLight) & 0xFF);
        byte lowerLow  = (byte) (lowerColor & 0xFF);

        byte[] frame = new byte[7];
        frame[0] = FH;
        frame[1] = channel;
        frame[2] = upperHigh;
        frame[3] = upperLow;
        frame[4] = lowerHigh;
        frame[5] = lowerLow;

        int sum = 0;
        for (int i = 0; i < 6; i++) {
            sum += (frame[i] & 0xFF);
        }
        frame[6] = (byte) (sum & 0xFF);

        StringBuilder sb = new StringBuilder();
        for (byte b : frame) {
            sb.append(String.format("%02X", b));
        }

        return sb.toString();
    }

    public void sendDate(String hexToSend) {
        if (SerialManage.getInstance() != null) {
            byte[] bytesToSend = hexStringToByteArray(hexToSend);
            String hexString = bytesToHex(bytesToSend);
            SerialManage.getInstance().send(hexString);
            saveFrame(FRAME_KEY,hexString);
        } else {
            Toast.makeText(this, R.string.port_manager_not_initialized, Toast.LENGTH_SHORT).show();
        }
    }
    private byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
    private void openSerial() {
        if (isSerialOpen) {
            // 关闭串口
            if (SerialManage.getInstance() != null) {
                SerialManage.getInstance().close();
                isSerialOpen = false;
                Toast.makeText(this, R.string.port_close, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, R.string.port_manager_not_initialized, Toast.LENGTH_SHORT).show();
            }
        } else {
            // 自动连接固定串口配置
            String ttySelected = "/dev/ttyUSB2";
            int baudRate = 9600;
            int dataBits = 8;
            int stopBits = 1;
            int parity = 0; // 0 表示无校验（N）

            if (SerialManage.getInstance() != null) {
                SerialManage.getInstance().close(); // 确保之前的串口已关闭
                SerialManage.getInstance().updateSerialPath(ttySelected, String.valueOf(baudRate));

                boolean isOpened = SerialManage.getInstance().open(ttySelected, baudRate, dataBits, stopBits, parity);
                if (isOpened) {
                    isSerialOpen = true;
                    Toast.makeText(this, R.string.port_opened_successfully, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, R.string.port_opened_failed, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, R.string.port_manager_not_initialized, Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void initializePasswords() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // 检查是否已经设置过密码
        if (!prefs.contains(SUPER_ADMIN_PASSWORD_KEY) || !prefs.contains(USER_PASSWORD_KEY)) {
            // 如果没有设置过密码，则设置默认密码
            editor.putString(SUPER_ADMIN_PASSWORD_KEY, superAdminPassword);
            editor.putString(USER_PASSWORD_KEY, userPassword);
            editor.apply(); // 保存数据
            Log.d("PasswordInit", "默认密码已初始化");
        }

        // 加载密码
        superAdminPassword = prefs.getString(SUPER_ADMIN_PASSWORD_KEY, "654321"); // 默认值为"654321"
        userPassword = prefs.getString(USER_PASSWORD_KEY, "000000"); // 默认值为"000000"
        Log.d("PasswordLoad", "Super Admin Password: " + superAdminPassword);
        Log.d("PasswordLoad", "User Password: " + userPassword);
    }
    private void loadPasswords() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        superAdminPassword = prefs.getString(SUPER_ADMIN_PASSWORD_KEY, "654321");
        userPassword = prefs.getString(USER_PASSWORD_KEY, "000000");
        saveSwitch = prefs.getInt(SWITCH_KEY, 0);
        frame = prefs.getString(FRAME_KEY,"");

        Log.d("PasswordLoad", "Super Admin Password: " + superAdminPassword);
        Log.d("PasswordLoad", "User Password: " + userPassword);
        Log.d("PasswordLoad", "saveSwitch: " + saveSwitch);
        Log.d("PasswordLoad", "saveSwitch: " + frame);
    }
    private void findId(){
        spinner = findViewById(R.id.ttys_spinner);
        btnSend = findViewById(R.id.btn_send);
        lightModeImage = findViewById(R.id.light_mode_image);
        lowerLamplight = findViewById(R.id.lower_lamplight);
        upperLamplight = findViewById(R.id.upper_lamplight);
        btnSettings = findViewById(R.id.btn_settings);
        btnSpeed = findViewById(R.id.btn_speed);
        btnTiming = findViewById(R.id.btn_timing);
        loginInputLayout = findViewById(R.id.login_input_layout);
        loginInput = findViewById(R.id.login_input);
        loginPhoto = findViewById(R.id.login_photo);
        screenLayout = findViewById(R.id.screen_layout);
        btnLogin = findViewById(R.id.btn_login);
        colorModeContainer = findViewById(R.id.color_mode_container);
        lightModeContainer = findViewById(R.id.light_mode_container);
    }
    private void layout(){
        spinner = findViewById(R.id.ttys_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.ttys,
                R.layout.spinner_item
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        int red = R.color.red;
        int green = R.color.green;
        int blue = R.color.blue;
        int white = R.color.white;
        int black = R.color.black;
        int purple = R.color.purple;
        int yellow = R.color.yellow;
        int cyan = R.color.cyan;
        int transparent = R.color.transparent;

        List<LightMode> colorModes = new ArrayList<>();

        // 单色常亮 (8个)
        colorModes.add(new LightMode(getString(R.string.off), transparent));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), red));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), green));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), blue));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), white));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), black));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), purple));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), yellow));
        colorModes.add(new LightMode(getString(R.string.solid_color_constant), cyan));

        // 单色呼吸渐变 (7个)
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), red));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), green));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), blue));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), white));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), purple));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), yellow));
        colorModes.add(new LightMode(getString(R.string.solid_color_breathing), cyan));

        // 双色交替渐变 (9个)
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), red, yellow));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), red, purple));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), red, cyan));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), green, cyan));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), green, yellow));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), green, purple));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), yellow, purple));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), yellow, cyan));
        colorModes.add(new LightMode(getString(R.string.dual_color_alternating), purple, cyan));

        // 三色渐变 (2个)
        colorModes.add(new LightMode(getString(R.string.tricolor_gradient),red, green, blue));
        colorModes.add(new LightMode(getString(R.string.tricolor_gradient), purple, yellow, cyan));

        // 其他模式 (各1个)
        colorModes.add(new LightMode(getString(R.string.seven_color_gradient)));
        colorModes.add(new LightMode(getString(R.string.seven_color_jump)));
        colorModes.add(new LightMode(getString(R.string.colorful_trail_run)));
        colorModes.add(new LightMode(getString(R.string.colorful_color_chase)));


        while (colorModes.size() < 30) {
            colorModes.addAll(colorModes);
        }
        colorModes = colorModes.subList(0, 30);

        lightModeContainer.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        colorModeContainer.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        LightModeAdapter.OnLightModeSelectedListener listener = new LightModeAdapter.OnLightModeSelectedListener() {
            @Override
            public void onLightModeSelected(LightMode lightMode, int containerId, int position, StringBuilder frameBuilder) {
                if (containerId == 1) {
                    upperColor = position; // 存储上部选中的模式
                    Log.d("MainActivity", "Upper Light Mode Selected: " + lightMode.getModeName() + " at position " + position);
                } else if (containerId == 2) {
                    lowerColor = position; // 存储下部选中的模式
                    Log.d("MainActivity", "Lower Light Mode Selected: " + selectedLightModeLower + " at position " + position);
                }
                Log.d("MainActivity", "upperColor " + upperColor + " lowerColor " + lowerColor);
            }

            @Override
            public void onFrameBuilt(String frame) {
                // 可以根据需要处理数据帧
            }
        };

        lightModeContainer.setAdapter(new LightModeAdapter(colorModes, 01, listener));
        colorModeContainer.setAdapter(new LightModeAdapter(colorModes, 02, listener));
    }


    private Runnable hideNavBarRunnable = new Runnable() {
        @Override
        public void run() {
            hideNavigationBar();
            handler.postDelayed(this, 1000);
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        handler.post(hideNavBarRunnable);
    }
    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(hideNavBarRunnable);
    }
    private void hideNavigationBar() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }
}
