package com.key.coolkeyboard.activity;

import static com.key.coolkeyboard.CoolKeyboardSkin.getContext;

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 android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.key.coolkeyboard.CoolKeyboardSkin;
import com.key.coolkeyboard.R;
import com.key.coolkeyboard.data.MydataBase;
import com.key.coolkeyboard.data.Otherdata;
import com.key.coolkeyboard.databinding.ActivityPreviewBinding;
import com.key.coolkeyboard.tool.Adcallback;
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.List;

public class PreviewActivity extends AppCompatActivity {
    ActivityPreviewBinding binding;
    private String name, preview, url, unzipPath;
    private Otherdata otherdata;
    private Boolean islike = false;
    private List<ATInterstitial> ads;

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

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_preview), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        AdManager.loadAllAd();
        Intent intent = getIntent();
        preview = intent.getStringExtra(StaticValue.KEY_PRE);
        name = intent.getStringExtra(StaticValue.KEY_NAME);
        url = intent.getStringExtra(StaticValue.KEY_URL);

        initData();
        initEvent();
    }



    private void showKey() {
        Toast.makeText(PreviewActivity.this, getString(R.string.set_successful), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, ShowKeyboardActivity.class);
        startActivity(intent);
        finish();
    }

    private void initEvent() {

        binding.previewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              AdManager.showTopOn(PreviewActivity.this, new onActionListener() {
                  @Override
                  public void onAction() {
                      downLoad();
                  }
              });
            }
        });

        binding.previewIslike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdManager.showTopOn(PreviewActivity.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        checkLike();
                    }
                });
            }
        });

    }

    private void checkLike() {
        if (!islike) {
            binding.previewIslike.setBackgroundResource(R.drawable.icon_prelike_check);
            islike = true;
            otherdata.setIslike(true);
            Mytool.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });
        } else {
            binding.previewIslike.setBackgroundResource(R.drawable.icon_prelike_uncheck);
            islike = false;
            otherdata.setIslike(false);
            Mytool.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });
        }
    }

    private void downLoad() {
        if (!Mytool.isStep1() || !Mytool.isStep2()) {

            Intent intent = new Intent(this, SettingActivity.class);
            startActivity(intent);
        } else {


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

    private void initData() {
        binding.download.setSelected(false);
        binding.previewTitle.setTypeface(Typeface.createFromAsset(getAssets(), "Baumans-Regular.ttf"));
        binding.previewTitle.setText(name);
        binding.imageProgress.setVisibility(View.VISIBLE);
        binding.previewImage.setVisibility(View.GONE);
        binding.downloadProgress.setVisibility(View.GONE);
        Mytool.runIO(new Runnable() {
            @Override
            public void run() {
                List<Otherdata> existingData = MydataBase.getInstance().myDAO().checklikelist(preview);
                if (!existingData.isEmpty()) {
                    otherdata = existingData.get(0);
                    islike = otherdata.getIslike();
                    boolean isdown = otherdata.getDownloaded();
                    if (islike) {
                        binding.previewIslike.setBackgroundResource(R.drawable.icon_prelike_check);
                    } else {
                        binding.previewIslike.setBackgroundResource(R.drawable.icon_prelike_uncheck);
                    }
                    if (isdown) {
                        binding.downloadText.setText(R.string.download_apply);
                        binding.downloadImage.setVisibility(View.GONE);
                    }
                    String path = StaticValue.PATH;
                    if (path.equals(otherdata.getPath())) {
                        binding.download.setSelected(true);
                        binding.downloadText.setText(R.string.download_text_using);
                        binding.download.setEnabled(false);
                    }
                }
            }
        });
        Glide.with(this)
                .asBitmap()
                .load(preview)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        binding.previewImage.setImageBitmap(resource);
                        binding.previewImage.setVisibility(View.VISIBLE);
                        binding.imageProgress.setVisibility(View.GONE);

                    }

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

                    }
                });
        File cacheDir = this.getCacheDir();
        unzipPath = cacheDir + "/" + name;

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }
}