package com.app.wallpaper.myact;

import static androidx.databinding.adapters.ViewBindingAdapter.setPadding;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Insets;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.app.wallpaper.R;
import com.app.wallpaper.databinding.ActivityViewBinding;
import com.app.wallpaper.donwload.ImageDownloadTask;
import com.app.wallpaper.getdata.SetData;
import com.app.wallpaper.mydao.AppDatabase;
import com.app.wallpaper.mydao.InterfaceDao;
import com.app.wallpaper.mydao.MyEntity;
import com.app.wallpaper.myfra.ViewFragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ViewActivity extends AppCompatActivity {
    private ActivityViewBinding binding;
    private int position, cataId, Id,position1;
    private WallpaperManager wallpaperManager;
    private String sourUrl;
    private InterfaceDao interfaceDao;
    private AppDatabase appDatabase;
    private MyEntity myEntitys = new MyEntity();
    private ImageDownloadTask downloadTask;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityViewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        intenttData();
        wallpaperManager = WallpaperManager.getInstance(this);
        appDatabase = AppDatabase.getDatabase(this);
        if (cataId != 0) {
            sourUrl = SetData.getCataDatas().get(cataId).getList().get(position).getSourceUrl();
        } else {
            sourUrl = SetData.getDataUrls().get(position).getSourceUrl();
        }
        showView();
        interfaceDao = appDatabase.interfaceDao();
        initJudge();
        binding.back.setOnClickListener(view -> finish());
        setButtonLisenner();
    }

    private void intenttData() {
        position1 = getIntent().getIntExtra("position1", 0);
        if (position1 != 0) {
            position = position1;
        }else {
            position = getIntent().getIntExtra("position", 0);
        }
        cataId = getIntent().getIntExtra("cataId", 0);
        Id = getIntent().getIntExtra("Id", -100);
        myEntitys = (MyEntity) getIntent().getSerializableExtra("imageUrl");
    }

    private void initJudge() {
        new Thread(new Runnable() {
            public void run() {
                if (myEntitys != null) {
                    MyEntity myEntity = interfaceDao.getImageSou(myEntitys.imageSou);
                    if (myEntity != null) {
                        binding.likeImg.setBackgroundResource(R.drawable.likede_ic);
                    }
                } else {
                    MyEntity myEntity = interfaceDao.getImageSou(sourUrl);
                    if (myEntity != null) {
                        binding.likeImg.setBackgroundResource(R.drawable.likede_ic);
                    }
                }
            }
        }).start();

    }
    private void setButtonLisenner() {
        binding.donwload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sourUrl != null) {
                    downloadTask = new ImageDownloadTask(getBaseContext(), ViewActivity.this);
                    downloadTask.execute(sourUrl);
                    binding.progressbar1.setVisibility(View.VISIBLE);
                } else {
                    Toast.makeText(ViewActivity.this, "Failed to download image...", Toast.LENGTH_SHORT).show();
                }
            }
        });
        binding.apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadPreview(sourUrl);
                binding.progressbar1.setVisibility(View.VISIBLE);
            }
        });
        binding.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (myEntitys == null) {
                            MyEntity myEntity1 = interfaceDao.getImageSou(sourUrl);
                            if (myEntity1 == null) {
                                if (cataId==0) {
                                    MyEntity myEntity = new MyEntity();
                                    myEntity.setImagePre(SetData.getDataUrls().get(position).getPreUrl());
                                    myEntity.setImageSou(sourUrl);
                                    new InsertImageTask().execute(myEntity);
                                }else {
                                    MyEntity myEntity = new MyEntity();
                                    myEntity.setImagePre(SetData.getCataDatas().get(cataId).getList().get(position).getPreUrl());
                                    myEntity.setImageSou(sourUrl);
                                    new InsertImageTask().execute(myEntity);
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        binding.likeImg.setBackgroundResource(R.drawable.likede_ic);
                                        Toast.makeText(ViewActivity.this, "Added successfully", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                interfaceDao.deleteUser(myEntity1);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        binding.likeImg.setBackgroundResource(R.drawable.like);
                                        Toast.makeText(ViewActivity.this, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        } else
                        {
                            MyEntity myEntity2 = myEntitys;
                            interfaceDao.deleteUser(myEntity2);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    binding.likeImg.setBackgroundResource(R.drawable.like);
                                    Toast.makeText(ViewActivity.this, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                }).start();
            }
        });
        binding.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain"); // 设置分享内容的类型为图片
                shareIntent.putExtra(Intent.EXTRA_TEXT, sourUrl); // 可以添加URL文本
                startActivity(Intent.createChooser(shareIntent, "Share pictures"));
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private class InsertImageTask extends AsyncTask<MyEntity, Void, Void> {
        @Override
        protected Void doInBackground(MyEntity... myEntities) {
            appDatabase.interfaceDao().insert(myEntities[0]);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

        }
    }
    private void showView() {
        ViewFragment viewFragment;
            if (myEntitys == null) {
                if (cataId == 0) {
                    viewFragment = ViewFragment.newInstance(SetData
                            .getDataUrls().get(position).getSourceUrl());
                } else {
                    viewFragment = ViewFragment.newInstance(SetData.
                            getCataDatas().get(cataId).getList().
                            get(position).getSourceUrl());
                }
            } else {
                viewFragment = ViewFragment.newInstance(myEntitys.getImageUrl2());
            }
        binding.viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return viewFragment;
            }

            @Override
            public int getCount() {
                return 1;
            }
        });
    }

    private void loadPreview(String preURl) {
        Glide.with(this)
                .asBitmap()
                .load(preURl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        binding.progressbar1.setVisibility(View.VISIBLE);
                        setPhoneWallpaper(resource);
                    }
                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        binding.progressbar1.setVisibility(View.GONE);
                    }
                });
    }
    private void setPhoneWallpaper(Bitmap bitmap) {
        try {
            wallpaperManager.setBitmap(bitmap);
            finish();
            Toast.makeText(this, "Setting wallpaper successfully", Toast.LENGTH_SHORT).show();
            binding.progressbar1.setVisibility(View.GONE);
        } catch (IOException ioException) {
            Toast.makeText(this, "Setting failed, ", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadTask != null && !downloadTask.isCancelled()) {
            downloadTask.cancel(true);
        }
    }

}