package com.key.coolkeyboard.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.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
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.google.android.material.tabs.TabLayout;
import com.key.coolkeyboard.CoolKeyboardSkin;
import com.key.coolkeyboard.R;
import com.key.coolkeyboard.adapter.PageAdapter;
import com.key.coolkeyboard.callback.RecommendDialogCallback;
import com.key.coolkeyboard.callback.StepDialogCallback;
import com.key.coolkeyboard.data.MydataBase;
import com.key.coolkeyboard.data.Otherdata;
import com.key.coolkeyboard.databinding.ActivityMainBinding;
import com.key.coolkeyboard.dialog.RecommendDialogFragment;
import com.key.coolkeyboard.dialog.StepDialogFragment;
import com.key.coolkeyboard.fragment.DownloadFragment;
import com.key.coolkeyboard.fragment.LikeFragment;
import com.key.coolkeyboard.fragment.MainFragment;
import com.key.coolkeyboard.tool.Mytool;
import com.key.coolkeyboard.tool.StaticValue;
import com.key.coolkeyboard.topon.AdManager;
import com.key.coolkeyboard.topon.onActionListener;

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

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    private List<Fragment> list = new ArrayList<>();

    private StepDialogFragment stepDialogFragment;
    private RecommendDialogFragment recommendDialogFragment;
    private Otherdata otherdata;
    private String unzipPath;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        AdManager.loadAllAd();
        Mytool.runIO(new Runnable() {
            @Override
            public void run() {
                otherdata = MydataBase.getInstance().myDAO().queryRandomItem();
                Log.d(CoolKeyboardSkin.TAG, "------000--otherdata="+otherdata);

            }
        });
        initData();
        if (Mytool.isStep1() && Mytool.isStep2()) {
            showToastDg();
        } else {
            showDg();
        }

    }

    private void showDg() {
        if (stepDialogFragment == null) {
            stepDialogFragment = StepDialogFragment.newInstance(MainActivity.this, new StepDialogCallback() {
                @Override
                public void onDisMiss() {
                    showToastDg();
                }
            });

        }
        stepDialogFragment.show(getSupportFragmentManager(), "");
    }


    private void showToastDg() {
        if (recommendDialogFragment == null) {
            recommendDialogFragment = RecommendDialogFragment.newInstance(MainActivity.this, new RecommendDialogCallback() {
                @Override
                public void onTryNow() {
                    binding.pbLoading.setVisibility(View.VISIBLE);
                    downLoad();
                }
            });

            if (otherdata != null) {
                recommendDialogFragment.setIm(otherdata.getPreview());
            }
        }

        File cacheDir = this.getCacheDir();
        unzipPath = cacheDir + "/" + otherdata.getTitle();

        if (otherdata != null) {
            recommendDialogFragment.setIm(otherdata.getPreview());
        }
        recommendDialogFragment.show(getSupportFragmentManager(), "");


    }

    private void downLoad() {
        Mytool.donwnZip(this, otherdata.getZipUrl(), (successful, resource) -> {
            if (successful) {
                Mytool.unZip(this, unzipPath, resource, (successful1, resDirPath) -> {
                    if (successful1) {
                        StaticValue.PATH = resDirPath;
                        otherdata.setDownloaded(true);
                        Mytool.runIO(new Runnable() {
                            @Override
                            public void run() {
                                MydataBase.getInstance().myDAO().update(otherdata);
                            }
                        });
                        showKey();
                    } else {
                        binding.pbLoading.setVisibility(View.GONE);
                        Toast.makeText(MainActivity.this, getString(R.string.text_zip_failed), Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                binding.pbLoading.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, getString(R.string.text_download_failed), Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void showKey() {
        if(recommendDialogFragment!= null){
            recommendDialogFragment.closeDialog();
        }
        binding.pbLoading.setVisibility(View.GONE);
        Toast.makeText(MainActivity.this, getString(R.string.set_successful), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, ShowKeyboardActivity.class);
        startActivity(intent);

    }


    private void initData() {

        list.add(new MainFragment());
        list.add(new LikeFragment());
        list.add(new DownloadFragment());
        PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), list);
        binding.mainViewpager.setAdapter(adapter);
        binding.mainTabLayout.setupWithViewPager(binding.mainViewpager);
        setMainTabIcons(binding.mainTabLayout);
        binding.mainViewpager.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 setTabIcons(final int position) {
        for (int i = 0; i < binding.mainTabLayout.getTabCount(); i++) {
            final TabLayout.Tab tab = binding.mainTabLayout.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.down_check : R.drawable.down_uncheck);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void setMainTabIcons(TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                switch (i) {
                    case 0:
                        tab.setIcon(R.drawable.home_check);
                        break;
                    case 1:
                        tab.setIcon(R.drawable.like_uncheck);
                        break;
                    case 2:
                        tab.setIcon(R.drawable.down_uncheck);
                        break;
                    default:
                        break;
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
