package com.key.simplekeyboard.activity;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.key.simplekeyboard.R;
import com.key.simplekeyboard.SimpleKeyboardSkins;
import com.key.simplekeyboard.adapter.ThumAdapter;
import com.key.simplekeyboard.data.MydataBase;
import com.key.simplekeyboard.data.Otherdata;
import com.key.simplekeyboard.fragment.MainFragment;
import com.key.simplekeyboard.tools.Mytools;
import com.key.simplekeyboard.tools.SpaceItem;
import com.key.simplekeyboard.tools.StaticValue;

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

public class PreviewActivity extends AppCompatActivity {
    private ImageView back, like, preimg, downimg;
    private ConstraintLayout download;
    private LinearLayout viewall;
    private TextView title;
    private RecyclerView prerv;
    private ProgressBar downpg, prepg;
    private String name, preview, url, unzipPath;
    private final Boolean[] islike = {false};
    private Otherdata otherdata;
    private List<Otherdata> prerandomlist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_pre), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        intView();

        List<Otherdata> othList = MainFragment.generateRandomOtherdata(0, 10);
        for (Otherdata data : othList) {
            if (prerandomlist.size() < 10) {
                prerandomlist.add(data);
            }
        }

        SpaceItem spaceItem = new SpaceItem(12, 12, 12);
        prerv.setAdapter(new ThumAdapter(this, prerandomlist));
        prerv.setLayoutManager(new GridLayoutManager(this, 2));
        prerv.addItemDecoration(spaceItem);
        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<Otherdata> existingData = MydataBase.getInstance().myDAO().checklikelist(preview);
                if (!existingData.isEmpty()) {
                    otherdata = existingData.get(0);
                    islike[0] = otherdata.getIslike();
                    if (islike[0]) {
                        like.setBackgroundResource(R.drawable.icon_pre_like_check);
                    } else {
                        like.setBackgroundResource(R.drawable.icon_pre_like_uncheck);
                    }
                }
            }
        });
        Glide.with(this)
                .asBitmap()
                .load(preview)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        preimg.setImageBitmap(resource);
                        preimg.setVisibility(View.VISIBLE);
                        title.setText(name);
                        prepg.setVisibility(View.GONE);
                    }

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

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

    private void intEvent() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLike();
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoad();
            }
        });
        viewall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PreviewActivity.this, AllActivity.class);
                startActivity(intent);
            }
        });
    }

    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, SettingActivity.class);
            startActivity(intent);
        } else {
            downpg.setVisibility(View.VISIBLE);
            downimg.setVisibility(View.GONE);
            Mytools.donwnZip(this, url, (successful, resource) -> {
                if (successful) {
                    Mytools.unZip(this, unzipPath, resource, (successful1, resDirPath) -> {
                        if (successful1) {
                            StaticValue.PATH = resDirPath;
                            Toast.makeText(PreviewActivity.this, getString(R.string.set_successful), Toast.LENGTH_SHORT).show();
                            downpg.setVisibility(View.GONE);
                            finish();
                        } 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();
                }
            });
        }
    }

    private void isLike() {
        if (!islike[0]) {
            like.setBackgroundResource(R.drawable.icon_pre_like_check);
            islike[0] = true;
            otherdata.setIslike(true);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });


        } else {
            like.setBackgroundResource(R.drawable.icon_pre_like_uncheck);
            islike[0] = false;
            otherdata.setIslike(false);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().myDAO().update(otherdata);
                }
            });
        }
    }

    private void intView() {
        preimg = findViewById(R.id.preview_image);
        like = findViewById(R.id.pre_like);
        back = findViewById(R.id.pre_back);
        download = findViewById(R.id.download);
        viewall = findViewById(R.id.pre_all);
        title = findViewById(R.id.pre_title);
        prerv = findViewById(R.id.pre_rv);
        downimg = findViewById(R.id.download_image);
        downpg = findViewById(R.id.download_progress);
        prepg = findViewById(R.id.image_progress);
        downpg.setVisibility(View.GONE);
        prepg.setVisibility(View.VISIBLE);
        preimg.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.e("zzj","1111111111111111");
    }
}