package com.exquisite.activity;


import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.exquisite.KeyboardSkin;
import com.exquisite.R;
import com.exquisite.adapter.PageAdapter;
import com.exquisite.data.Mydata;
import com.exquisite.data.MydataBase;
import com.exquisite.data.StaticValue;
import com.exquisite.tools.Mytools;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private Dialog toastDialog;
    private Mydata otherdata;
    private String unzipPath;
    private Dialog dialog;
    private BroadcastReceiver broadcastReceiver;
    private static final InputMethodManager methodManager = (InputMethodManager) KeyboardSkin.app.getSystemService(Context.INPUT_METHOD_SERVICE);

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.mainactivity), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        tabLayout = findViewById(R.id.main_tabLayout);
        ViewPager viewPager = findViewById(R.id.main_viewpager);
        PageAdapter adapter = new PageAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        showDg();


        setTabIcons(0);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setTabIcons(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void showDg() {
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog);
        dialog.setCancelable(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        dialog.setCanceledOnTouchOutside(false);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateDialogContent();
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED));

        dialog.findViewById(R.id.step1).setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
            startActivity(intent);
        });
        dialog.findViewById(R.id.step2).setOnClickListener(v -> methodManager.showInputMethodPicker());
        dialog.findViewById(R.id.setting_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDg();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Mytools.runIO(new Runnable() {
                    @Override
                    public void run() {
                        List<Mydata> list1 = MydataBase.getInstance().myDAO().getAlldata();
                        otherdata = list1.get(666);
                        if (toastDialog == null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToastDg();
                                }
                            });

                        }
                    }
                });
            }
        });
        dialog.show();
        dialog.getWindow().setAttributes(lp);

        updateDialogContent();
    }

    private void hideDg() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void updateDialogContent() {
        boolean step1 = Mytools.isStep1();
        boolean step2 = Mytools.isStep2();
        dialog.findViewById(R.id.step1).setSelected(step1);
        dialog.findViewById(R.id.step2).setSelected(step2);
        updateDialogImages();
    }

    private void updateDialogImages() {
        if (Mytools.isStep2()) {
            dialog.findViewById(R.id.step2_image).setVisibility(View.VISIBLE);
        } else {
            dialog.findViewById(R.id.step2_image).setVisibility(View.GONE);
        }
        if (Mytools.isStep1()) {
            dialog.findViewById(R.id.step1_image).setVisibility(View.VISIBLE);
        } else {
            dialog.findViewById(R.id.step1_image).setVisibility(View.GONE);
        }
    }


    private void showToastDg() {
        toastDialog = new Dialog(this);
        toastDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        toastDialog.setContentView(R.layout.toast_dialog);
        toastDialog.setCancelable(true);
//        toastDialog.getWindow().setGravity(Gravity.BOTTOM);
        toastDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(toastDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        ImageView toastImageView = toastDialog.findViewById(R.id.toast_dialog_image);
        Glide.with(MainActivity.this)
                .asBitmap()
                .load(otherdata.getPreview())
                .placeholder(R.mipmap.logo)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        toastImageView.setImageBitmap(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });

        toastDialog.setCanceledOnTouchOutside(false);
        toastDialog.findViewById(R.id.toast_dialog_cons).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoad();
            }
        });
        toastDialog.findViewById(R.id.toast_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (toastDialog != null && toastDialog.isShowing()) {
                toastDialog.dismiss();
//                }
            }
        });
        File cacheDir = this.getCacheDir();
        unzipPath = cacheDir + "/" + otherdata.getTitle();

        if (toastDialog != null) {
            toastDialog.show();
        }

        toastDialog.getWindow().setAttributes(lp);
    }


    private void downLoad() {
        if (!Mytools.isStep1() || !Mytools.isStep2()) {
//            Toast.makeText(this, getString(R.string.text_hint), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, KeyBoardSettingsActivity.class);
            startActivity(intent);
        } else {
            Mytools.donwnZip(this, otherdata.getZipUrl(), (successful, resource) -> {
                if (successful) {
                    Mytools.unZip(this, unzipPath, resource, (successful1, resDirPath) -> {
                        if (successful1) {
                            StaticValue.PATH = resDirPath;
                            otherdata.setDownloaded(true);
                            otherdata.setPath(resDirPath);
                            Mytools.runIO(new Runnable() {
                                @Override
                                public void run() {
                                    MydataBase.getInstance().myDAO().update(otherdata);
                                }
                            });
                            showKey();
                        } else {
                            Toast.makeText(MainActivity.this, getString(R.string.text_zip_failed), Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Toast.makeText(MainActivity.this, getString(R.string.text_download_failed), Toast.LENGTH_SHORT).show();

                }
            });
        }

    }

    private void setTabIcons(final int position) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            final TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                switch (i) {
                    case 0:
                        tab.setIcon(position == 0 ? R.drawable.home_check : R.drawable.home_uncheck);
                        break;
                    case 1:
                        tab.setIcon(position == 1 ? R.drawable.like_check : R.drawable.like_uncheck);
                        break;
                    case 2:
                        tab.setIcon(position == 2 ? R.drawable.setting_check : R.drawable.setting_uncheck);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void showKey() {
        Toast.makeText(MainActivity.this, getString(R.string.set_successful), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, ShowKeyboardActivity.class);
        intent.putExtra(StaticValue.KEY_ISshow, 1);
        startActivity(intent);

    }


    @Override
    protected void onResume() {
        super.onResume();
        updateDialogContent();
//        Log.e("zzj", "---a app get is---" + KeyboardSkin.a);
        if (KeyboardSkin.a == 1) {
            if (toastDialog != null) {
                toastDialog.dismiss();
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        KeyboardSkin.a = 0;
    }
}