package com.app.duck.ui;

import static com.app.duck.Config.BREATH_TAG;
import static com.app.duck.Config.INTENT_EDIT_INI;
import static com.app.duck.Config.PHONE_TAG;
import static com.app.duck.Config.SMS_UPLOAD_TAG;
import static com.app.duck.Config.WEBSOCKET_STATUS_TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.app.duck.BaseActivity;
import com.app.duck.BuildConfig;
import com.app.duck.R;
import com.app.duck.database.Config;
import com.app.duck.databinding.ActivityMainBinding;
import com.app.duck.dialog.DialogManager;
import com.app.duck.util.CheckInboxWorker;
import com.app.duck.util.HeartbeatWorker;
import com.app.duck.util.HxUtils;
import com.app.duck.util.TgBot;
import com.app.duck.util.WsManager;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LanguageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.navigation.NavigationView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.Locale;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements NavigationView.OnNavigationItemSelectedListener {

    public static Locale EN_LOCAL = Locale.ENGLISH;//英语
    public static Locale CN_LOCAL = Locale.CHINESE;//简体中文
    public static String[] DISPLAY_LANGUAGE_ARRAY = new String[]{EN_LOCAL.getDisplayLanguage(EN_LOCAL), CN_LOCAL.getDisplayLanguage(CN_LOCAL)};
    public static Locale[] LOCAL_ARRAY = new Locale[]{EN_LOCAL, CN_LOCAL};
    private AppBarConfiguration mAppBarConfiguration;
    private Context context = this;
    private androidx.lifecycle.Observer<String> observer2;
    private androidx.lifecycle.Observer<String> observer3;
    private androidx.lifecycle.Observer<String> observer4;
    private androidx.lifecycle.Observer<String> observer5;
    private Locale currentLocal = EN_LOCAL;

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        setSupportActionBar(b.appBarMain.toolbar);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home)
                .setOpenableLayout(b.drawerLayout)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(b.navView, navController);
        b.navView.setNavigationItemSelectedListener(this);
        View headerView = b.navView.getHeaderView(0);
        TextView codeTv = headerView.findViewById(R.id.versionCodeTv);
        codeTv.setText(AppUtils.getAppVersionName() + " - " + AppUtils.getAppVersionCode());
        b.appBarMain.contentMain.phoneTv.setOnClickListener(view -> {
            DialogManager.phoneEditDialog();
        });

        b.appBarMain.contentMain.workTv.setSelected(true);
        b.appBarMain.contentMain.workTv2.setSelected(true);
        b.appBarMain.contentMain.workTv3.setSelected(true);
        b.appBarMain.contentMain.phoneTv.setSelected(true);
        observer2 = s -> b.appBarMain.contentMain.workTv.setText(s);
        observer3 = s -> b.appBarMain.contentMain.workTv2.setText(s);
        observer4 = s -> b.appBarMain.contentMain.workTv3.setText(s);
        observer5 = s -> {
            b.appBarMain.contentMain.phoneTv.setText(s);
            WsManager.closeWebSocket();
        };

        LiveEventBus.get(BREATH_TAG, String.class).observe(this, observer2);
        LiveEventBus.get(WEBSOCKET_STATUS_TAG, String.class).observe(this, observer3);
        LiveEventBus.get(SMS_UPLOAD_TAG, String.class).observeSticky(this, observer4);
        LiveEventBus.get(PHONE_TAG, String.class).observe(this, observer5);
        b.appBarMain.contentMain.phoneTv.setText(getPhone());
        CheckInboxWorker.start();
        HeartbeatWorker.start();
        startForegroundService();
        checkForUpdate();
        HxUtils.checkForUpdateBotConfig();


        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LiveEventBus.get(BREATH_TAG, String.class).removeObserver(observer2);
        LiveEventBus.get(WEBSOCKET_STATUS_TAG, String.class).removeObserver(observer3);
        LiveEventBus.get(SMS_UPLOAD_TAG, String.class).removeObserver(observer4);
        LiveEventBus.get(PHONE_TAG, String.class).removeObserver(observer5);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_text:
                String content = "[common]\n" +
                        "server_addr = {{FRPC_IP}}\n" +
                        "server_port = 7000\n" +
                        "token = 123678asbsfd\n" +
                        "\n" +
                        "\n" +
                        "[socks5_proxy_tunnel{{FRPC_PORT}}]\n" +
                        "type = tcp\n" +
                        "remote_port = {{FRPC_PORT}}\n" +
                        "plugin = socks5";
                content = content.replace("{{FRPC_IP}}", BuildConfig.FRPC_IP).replace("{{FRPC_PORT}}", BuildConfig.FRPC_PORT);

                LiveEventBus.get(INTENT_EDIT_INI).post(new Config(content));
                startActivity(new Intent(MainActivity.this, IniEditActivity.class));
                break;
            case R.id.action_accessibility:
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(intent);
                break;
            case R.id.action_accessibility2:
                Intent intent2 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivity(intent2);
                break;
            case R.id.action_update_log_config:
                HxUtils.checkForUpdateBotConfig();
//                demo();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void demo() {
        WsManager.sendSMSDelayed(TimeUtils.getNowString(), TimeUtils.getNowString(), "13385739331");
//        WsManager.getOutBoxSMS("12312321", "5");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.logcat_push:
                new TgBot("", false);
                return true;
            case R.id.about:
                HxUtils.checkForUpdate(context, true);
                break;
            case R.id.change:
                int checkedItem = 0;
                new MaterialAlertDialogBuilder(this).
                        setTitle(R.string.change)
                        .setNeutralButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss())
                        .setPositiveButton(R.string.ok, (dialogInterface, i) -> {
                            if (LanguageUtils.isAppliedLanguage()) {
                                LanguageUtils.applyLanguage(currentLocal, false);
                                dialogInterface.dismiss();
                            } else {
                                LanguageUtils.applyLanguage(currentLocal, false);
                            }
                        }).setSingleChoiceItems(DISPLAY_LANGUAGE_ARRAY, checkedItem,
                                (dialogInterface, i) -> currentLocal = LOCAL_ARRAY[i]).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }


}
