package com.example.prettywallpapers.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
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.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

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.myvalue.MyValues;
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.IOException;
import java.io.OutputStream;
import java.util.List;

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

public class PreviewActivity 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 PrettyPaperEntity entity;
    private PrettyPaper resource;
    private boolean islike1 = false;
    private Dialog dialog;

    @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);
        gotoGetData();


        image_hert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    image_hert.setSelected(!image_hert.isSelected());
                    if (image_hert.isSelected()) {
                        entity.setPaperlike(true);
                        MyTool.runIO(new Runnable() {
                            @Override
                            public void run() {
                                PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().UpdateLikePaper(entity);
                                Log.d("dhn","----islike"+entity.getPaperlike());
                            }
                        });
                        Toast.makeText(PreviewActivity.this,getString(R.string.like_success),Toast.LENGTH_SHORT).show();
                    } else {
                        entity.setPaperlike(false);
                        MyTool.runIO(new Runnable() {
                            @Override
                            public void run() {
                                PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().UpdateLikePaper(entity);
                                Log.d("dhn","----islike"+entity.getPaperlike());
                            }
                        });
                        Toast.makeText(PreviewActivity.this,getString(R.string.like_cancle), Toast.LENGTH_SHORT).show();
                    }
            }
        });

        image_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(PreviewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(PreviewActivity.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();
                showdialog();
            }
        });
        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 gotoGetData() {
        Intent intent = getIntent();
        image = intent.getStringExtra(MyValues.PAPER_IMAGE);
        MyTool.runIO(new Runnable() {
            @Override
            public void run() {
                entity = PrettyPaperDatabase.getPrettyPaperDatabase().getPrettyPaperDao().queryimage(image);
                Log.d("dhn","--------------entity--"+entity.getPaperlike());
                    if (entity.getPaperlike()) {
                        image_hert.setSelected(true);
                    } else {
                        image_hert.setSelected(false);
                    }

            }
        });

        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 showad() {
        AdManager.showAD(PreviewActivity.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(PreviewActivity.this, getString(R.string.set_wait), Toast.LENGTH_SHORT).show();
                    if (image != null) {
                        loadPreview(image);
                    } else {
                        Toast.makeText(PreviewActivity.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 LoadLockPreview(String preURl) {
        Glide.with(this)
                .asBitmap()
                .load(preURl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        setLockWallPaper(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 setLockWallPaper(Bitmap lockbitmap) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                wallpaperManager.setBitmap(lockbitmap,null,true,WallpaperManager.FLAG_LOCK);
                Toast.makeText(this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
            }else {
                wallpaperManager.setBitmap(lockbitmap);
            }
        } catch (Exception e) {
            Toast.makeText(this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
        }
    }
    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(PreviewActivity.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(PreviewActivity.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    } else {
                        Looper.prepare();
                        Toast.makeText(PreviewActivity.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    @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();
            }
        }
    }


    private void showdialog() {
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.switch_set_type);
        dialog.setCancelable(false);
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.findViewById(R.id.type_home).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (image != null) {
                    loadPreview(image);
                    dialog.cancel();
                } else {
                    Toast.makeText(PreviewActivity.this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
        dialog.findViewById(R.id.type_screen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (image != null) {
                    LoadLockPreview(image);
                    dialog.cancel();
                } else {
                    Toast.makeText(PreviewActivity.this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
        dialog.findViewById(R.id.type_both).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (image != null) {
                    loadPreview(image);
                    LoadLockPreview(image);
                    dialog.cancel();
                } else {
                    Toast.makeText(PreviewActivity.this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
        dialog.findViewById(R.id.close_dialog_image).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.show();
        dialog.getWindow().setAttributes(lp);

    }
}