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.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
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.exquisite.KeyboardSkin;
import com.exquisite.adapter.ThumAdapter;

import com.exquisite.callback.Adcallback;
import com.exquisite.data.Mydata;
import com.exquisite.data.MydataBase;
import com.exquisite.data.StaticValue;
import com.exquisite.R;

import com.exquisite.tools.Mytools;
import com.exquisite.tools.SpaceItem;

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

public class PreviewActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout back, viewall, settings;
    private RecyclerView previewrv;
    private ImageView imageView;
    private String name;
    private String preview;
    private String url;
    private String unzipPath;
    private TextView textView;
    private ProgressBar progressBarPreview;

    private ProgressBar progressBarDownload;
    private List<ATInterstitial> ads;
    private ThumAdapter thumAdapter;
    private ImageView like;
    private Boolean islike = false;
    private Mydata otherdata;
    private TextView downloadText;
    private ImageView downImage;
    private List<Mydata> newList = new ArrayList<>();
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.preview), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ads = KeyboardSkin.lodAd();

        intView();

        imageView.setVisibility(View.GONE);
        progressBarPreview.setVisibility(View.VISIBLE);
        progressBarDownload.setVisibility(View.GONE);

        SpaceItem spaceItem = new SpaceItem(10, 20, 10);
        previewrv.setLayoutManager(new GridLayoutManager(PreviewActivity.this, 2));
        previewrv.addItemDecoration(spaceItem);

        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                List<Mydata> mydata = MydataBase.getInstance().myDAO().getAlldata();
                Collections.shuffle(mydata);
                newList   = mydata.subList(0, 10);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        thumAdapter = new ThumAdapter(PreviewActivity.this, newList);
                        previewrv.setAdapter(thumAdapter);
                    }
                });

            }
        });
//        MydataBase.getInstance().myDAO().getAll().observe(this, new Observer<List<Mydata>>() {
//            @Override
//            public void onChanged(List<Mydata> mydata) {
//
//
//
//            }
//        });

        Intent intent = getIntent();
        preview = intent.getStringExtra(StaticValue.KEY_PRE);
        name = intent.getStringExtra(StaticValue.KEY_NAME);
        url = intent.getStringExtra(StaticValue.KEY_URL);

        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                List<Mydata> existingData = MydataBase.getInstance().myDAO().checklikelist(preview);
                if (!existingData.isEmpty()) {
                    otherdata = existingData.get(0);
                    islike = otherdata.getIslike();
                    boolean isdown = otherdata.getDownloaded();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (islike) {
                                like.setBackgroundResource(R.drawable.icon_like_check);
                            } else {
                                like.setBackgroundResource(R.drawable.icon_like_uncheck);
                            }
                            if (isdown) {
                                downloadText.setText(R.string.download_apply);
                                downImage.setVisibility(View.GONE);
                            }
                            String path = StaticValue.PATH;
                            if (path.equals(otherdata.getPath())) {
//                        binding.download.setSelected(true);
                                downloadText.setText(R.string.download_text_using);
                                settings.setEnabled(false);
                            }
                        }
                    });

                }
            }
        });

        Glide.with(this)
                .asBitmap()
                .load(preview)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        imageView.setImageBitmap(resource);
                        imageView.setVisibility(View.VISIBLE);
                        textView.setText(name);
                        progressBarPreview.setVisibility(View.GONE);
                    }

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

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

    private void intEvent() {
        back.setOnClickListener(this);
        viewall.setOnClickListener(this);
        settings.setOnClickListener(this);
        like.setOnClickListener(this);
    }

    private void intView() {
        downImage = findViewById(R.id.pre_down_image);
        downloadText = findViewById(R.id.pre_down_text);
        like = findViewById(R.id.preview_islike);
        back = findViewById(R.id.detail_back);
        imageView = findViewById(R.id.preview_image);
        viewall = findViewById(R.id.preview_all);
        previewrv = findViewById(R.id.detail_rv);
        textView = findViewById(R.id.image_text);
        settings = findViewById(R.id.detail_setting);
        progressBarPreview = findViewById(R.id.image_progress);
        progressBarDownload = findViewById(R.id.download_progress);
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_back:
                finish();
                break;
            case R.id.preview_all:
                Intent intent = new Intent(PreviewActivity.this, AllActivity.class);
                startActivity(intent);
                break;
            case R.id.preview_islike:
                checkLike();
                break;
            case R.id.detail_setting:
                download();
                break;
        }
    }

    private void checkLike() {
        if (!islike) {
            like.setBackgroundResource(R.drawable.icon_like_check);
            islike = true;
            otherdata.setIslike(true);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });
        } else {
            like.setBackgroundResource(R.drawable.icon_like_uncheck);
            islike = false;
            otherdata.setIslike(false);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });
        }
    }

    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 showAd() {
        ATInterstitial mInterstitialAd = Mytools.onCache(ads);
        if (mInterstitialAd == null) {
            showKey();
        } else {
            if (mInterstitialAd.isAdReady()) {
                Mytools.setCallback(mInterstitialAd, new Adcallback() {
                    @Override
                    public void onShowFail(AdError ad) {
                        showKey();
                    }

                    @Override
                    public void onAdHidden() {
                        showKey();
                    }
                });
                mInterstitialAd.show(this);
            } else {
                mInterstitialAd.load();
            }
        }

    }

    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 {
            progressBarDownload.setVisibility(View.VISIBLE);
            Mytools.donwnZip(this, url, (successful, resource) -> {
                if (successful) {
                    Mytools.unZip(this, unzipPath, resource, (successful1, resDirPath) -> {
                        if (successful1) {
                            StaticValue.PATH = resDirPath;
                            progressBarDownload.setVisibility(View.GONE);
                            showAd();

                        }
                    });
                }
            });
        }
    }


}