package com.example.prettywallpapers.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.example.prettywallpapers.R;
import com.example.prettywallpapers.list.PrettyPaper;
import com.example.prettywallpapers.listener.SwitchType;
import com.example.prettywallpapers.myvalue.MyValues;
import com.example.prettywallpapers.room.PrettyPaperDao;
import com.example.prettywallpapers.room.PrettyPaperDatabase;
import com.example.prettywallpapers.room.PrettyPaperEntity;
import com.example.prettywallpapers.room.mytool;
import com.example.prettywallpapers.toponad.AdManager;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class PrettyPaperActivity extends AppCompatActivity {

    private RelativeLayout relative_main;
    private TextView text_set;
    private ImageView paper_image;
    private WallpaperManager wallpaperManager;
    private ImageView image_down;
    private ImageView image_share;
    private String image;
    private ImageView image_hert;
    private ImageView imageView_back;
    private boolean like = true;
    private PrettyPaperDatabase db;
    private boolean liked;
    private List<PrettyPaper> likelist;
    private List<PrettyPaperEntity> LIST;
    private PrettyPaper resource;
    private boolean islike1 = false;
    private PrettyPaperEntity one;
    private SwitchType switchType;
    private String switchtype;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //保存图片到相册
                downPreview(image);
            } else {
                Toast.makeText(this, "你拒绝了该权限，无法保存图片！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pretty_paper);
        relative_main =findViewById(R.id.paper_main);
        init();
        text_set = findViewById(R.id.text_set);
        wallpaperManager = WallpaperManager.getInstance(this);
        paper_image = findViewById(R.id.paper_image);
        image_down = findViewById(R.id.image_down);
        image_share = findViewById(R.id.image_share);
        imageView_back = findViewById(R.id.paper_back);
        image_hert = findViewById(R.id.image_heart);
        image_hert.setBackgroundResource(R.drawable.unselect_like);
        gotoGetData();


        image_hert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!islike1) {
                    image_hert.setBackgroundResource(R.drawable.unselect_like);
                    islike1 = true;
                    mytool.runIO(new Runnable() {
                        @Override
                        public void run() {
                            PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().deletelike(image);
                        }
                    });
                } else {
                    image_hert.setBackgroundResource(R.drawable.select_like);
                    islike1 = false;
                    PrettyPaperEntity prettyPaperEntity = new PrettyPaperEntity();
                    prettyPaperEntity.setPaperlike(like);
                    prettyPaperEntity.setImage(image);
                    mytool.runIO(new Runnable() {
                        @Override
                        public void run() {
                            PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().insertLikeData(prettyPaperEntity);
                        }
                    });
                    //Toast.makeText(PrettyPaperActivity.this,getString(R.string.like_success),Toast.LENGTH_LONG).show();
                }
            }
        });


        image_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(PrettyPaperActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(PrettyPaperActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                } else {
                    //保存图片到相册
                    downPreview(image);
                }
            }
        });



        text_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showad();
            }
        });
        image_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareImage();
            }
        });
        imageView_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void showad() {
        AdManager.showAD(PrettyPaperActivity.this, new Function1<Integer, Unit>() {
            @Override
            public Unit invoke(Integer integer) {
                if (integer == AdManager.type_no_cache || integer == AdManager.type_show_close || integer == AdManager.type_show_fail) {
                    Toast.makeText(PrettyPaperActivity.this, getString(R.string.set_wait), Toast.LENGTH_SHORT).show();
                    if (image != null) {
                        loadPreview(image);
                    } else {
                        Toast.makeText(PrettyPaperActivity.this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
                    }
                }
                return null;
            }
        });
    }

    private void loadPreview(String image) {
            Glide.with(this)
                    .asBitmap()
                    .load(image)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            setPhoneWallpaper(resource);

                        }
                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                        }
                    });
        }
    private void downPreview(String preURl) {
        Glide.with(this)
                .asBitmap()
                .load(preURl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        SaveImage(resource);
                    }


                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
    }
    private void setPhoneWallpaper(Bitmap bitmap) {
        try {
            wallpaperManager.setBitmap(bitmap);
            Toast.makeText(this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
        } catch (IOException ioException) {
            Toast.makeText(this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
        }
    }

    private void gotoGetData() {
        Intent intent = getIntent();
        image = intent.getStringExtra(MyValues.PAPER_IMAGE);
        mytool.runIO(new Runnable() {
            @Override
            public void run() {
                LIST = PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().queryimage(image);
                if (LIST.isEmpty()) {

                } else {
                    image_hert.setBackgroundResource(R.drawable.select_like);
                    islike1 = true;

                }
            }
        });


        Glide.with(this).load(image).addListener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).into(paper_image);
    }
    private void init() {
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        relative_main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }
    public void shareImage(){
            Intent sharedIntent = new Intent();
            sharedIntent.setAction(Intent.ACTION_SEND);
            sharedIntent.setType("text/*");
            sharedIntent.putExtra(Intent.EXTRA_TEXT,image);	//设置要分享的内容
            startActivity(Intent.createChooser(sharedIntent, "Share"));
    }

    private void SaveImage(Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Uri saveUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                    if (TextUtils.isEmpty(saveUri.toString())) {
                        Looper.prepare();
                        Toast.makeText(PrettyPaperActivity.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                    OutputStream outputStream = getContentResolver().openOutputStream(saveUri);
                    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                        Looper.prepare();
                        Toast.makeText(PrettyPaperActivity.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    } else {
                        Looper.prepare();
                        Toast.makeText(PrettyPaperActivity.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}