package com.makeeasy.dpandstatus;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_MEDIA_IMAGES;
import static android.Manifest.permission.SET_WALLPAPER;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.makeeasy.dpandstatus.Constant.BASE_URL;
import static com.makeeasy.dpandstatus.Constant.SHARE_TEXT;
import static com.makeeasy.dpandstatus.Constant.getAdSize;

import android.app.WallpaperManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.AdapterStatus;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.makeeasy.dpandstatus.model.Photo;
import com.makeeasy.dpandstatus.service.FavouriteList;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class PhotoActivity extends AppCompatActivity {

    private int swipe_count = 0;
    public static Photo selected_photo;
    public static List<Object> photoList;
    private InterstitialAd mInterstitialAd;
    private static final int MENU_ITEM = 5510;
    private static final int NATIVE_AD = 5511;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        MobileAds.initialize(this, initializationStatus -> {
            Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
            for (String adapterClass : statusMap.keySet()) {
                AdapterStatus status = statusMap.get(adapterClass);
                assert status != null;
            }
            AdView adView = new AdView(this);
            adView.setAdUnitId(getString(R.string.banner_id));
            ((FrameLayout)findViewById(R.id.adView)).addView(adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.setAdSize(getAdSize(this));
            adView.loadAd(adRequest);
        });loadInterstitialAds();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null) {
            getSupportActionBar().setTitle(selected_photo.getCategory());
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        toolbar.setNavigationOnClickListener(view -> finish());
        ViewPager2 viewPager = findViewById(R.id.viewPager);
        viewPager.setAdapter(new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            @Override
            public int getItemViewType(int position) {
                Object item = photoList.get(position);
                if (item instanceof NativeAd) {
                    return NATIVE_AD;
                } else {
                    return MENU_ITEM;
                }
            }
            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                switch (viewType) {
                    case NATIVE_AD:
                        View nativeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adunified,parent,false);
                        return new NativeViewHolder(nativeView);
                    case MENU_ITEM:
                    default:
                        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.page,parent,false);
                        return new PhotoView(itemView);
                }
            }
            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                switch (getItemViewType(position)) {
                    case NATIVE_AD:
                        NativeAd nativeAd = (NativeAd) photoList.get(position);
                        populateNativeAdView(nativeAd, ((NativeViewHolder) holder).getAdView());
                        break;
                    case MENU_ITEM:
                    default:
                        PhotoView photoView = (PhotoView) holder;
                        Photo photo = (Photo) photoList.get(position);String key;
                        Picasso.get().load(BASE_URL + "upload/" + photo.getImage()).fit().into(photoView.imageView);
                        if (photo.getCategory().equalsIgnoreCase("Favourite")) {
                            key = photo.getId();
                        } else {
                            key = photo.getCategory() + photo.getId();
                        }
                        if (FavouriteList.isContains(PhotoActivity.this,key)) {
                            photoView.like.setBackgroundResource(R.drawable.liked);
                        } else {
                            photoView.like.setBackgroundResource(R.drawable.like);
                        }
                        photoView.like.setOnClickListener(view -> {
                            if (FavouriteList.isContains(PhotoActivity.this,key)) {
                                FavouriteList.remove(PhotoActivity.this,key);
                                photoView.like.setBackgroundResource(R.drawable.like);
                            } else {
                                FavouriteList.add(PhotoActivity.this,key,photo.getImage());
                                photoView.like.setBackgroundResource(R.drawable.liked);
                            }
                        });
                        photoView.wall.setOnClickListener(view -> {
                            if (ContextCompat.checkSelfPermission(PhotoActivity.this,SET_WALLPAPER) == PackageManager.PERMISSION_GRANTED) {
                                WallpaperManager wallpaperManager = WallpaperManager.getInstance(PhotoActivity.this);
                                Picasso.get().load(BASE_URL + "upload/" + photo.getImage()).into(new Target() {
                                    @Override
                                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                        try {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                                wallpaperManager.setBitmap(bitmap,null,false,WallpaperManager.FLAG_SYSTEM);
                                            } else {
                                                wallpaperManager.setBitmap(bitmap);
                                            }
                                            makeText(PhotoActivity.this,"Home Screen Wallpaper Changed",LENGTH_SHORT).show();
                                        } catch (IOException e) {
                                            makeText(PhotoActivity.this,e.getMessage(),LENGTH_SHORT).show();
                                        }
                                    }
                                    @Override
                                    public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                                        makeText(PhotoActivity.this,e.getMessage(),LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onPrepareLoad(Drawable placeHolderDrawable) {}
                                });
                            } else {
                                makeText(PhotoActivity.this,"Accept Permission first",LENGTH_SHORT).show();
                                ActivityCompat.requestPermissions(PhotoActivity.this,new String[]{SET_WALLPAPER},1);
                            }
                        });
                        photoView.save.setOnClickListener(view -> {
                            String permission;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                permission = READ_MEDIA_IMAGES;
                            } else {
                                permission = READ_EXTERNAL_STORAGE;
                            }
                            if (ContextCompat.checkSelfPermission(PhotoActivity.this,permission) == PackageManager.PERMISSION_GRANTED) {
                                Picasso.get().load(BASE_URL + "upload/" + photo.getImage()).into(new Target() {
                                    @Override
                                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                        String title = photo.getCategory() + photo.getId();
                                        String description = "This is saved from " + getString(R.string.app_name) + " App";
                                        String path = MediaStore.Images.Media.insertImage(getContentResolver(),bitmap,title,description);
                                        makeText(PhotoActivity.this,"Saved in " + path,LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                                        makeText(PhotoActivity.this,e.getMessage(),LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onPrepareLoad(Drawable placeHolderDrawable) {}
                                });
                            } else {
                                makeText(PhotoActivity.this,"Accept Permission first",LENGTH_SHORT).show();
                                ActivityCompat.requestPermissions(PhotoActivity.this,new String[]{WRITE_EXTERNAL_STORAGE,permission}, 2);
                            }
                        });
                        photoView.share.setOnClickListener(view -> {
                            String permission;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                permission = READ_MEDIA_IMAGES;
                            } else {
                                permission = READ_EXTERNAL_STORAGE;
                            }
                            if (ContextCompat.checkSelfPermission(PhotoActivity.this,permission) == PackageManager.PERMISSION_GRANTED) {
                                Picasso.get().load(BASE_URL + "upload/" + photo.getImage()).into(new Target() {
                                    @Override
                                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                        String title = photo.getCategory() + photo.getId();
                                        String description = "This is saved from " + getString(R.string.app_name) + " App";
                                        String path = MediaStore.Images.Media.insertImage(getContentResolver(),bitmap,title,description);
                                        startActivity(Intent.createChooser(new Intent(Intent.ACTION_SEND).setType("image/jpg")
                                                .putExtra(Intent.EXTRA_STREAM,Uri.parse(path)).putExtra(Intent.EXTRA_TEXT,SHARE_TEXT + getPackageName()),"Share"));
                                    }
                                    @Override
                                    public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                                        makeText(PhotoActivity.this,e.getMessage(),LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onPrepareLoad(Drawable placeHolderDrawable) {}
                                });
                            } else {
                                makeText(PhotoActivity.this,"Accept Permission first",LENGTH_SHORT).show();
                                ActivityCompat.requestPermissions(PhotoActivity.this,new String[]{WRITE_EXTERNAL_STORAGE,permission}, 2);
                            }
                        });
                }
            }
            @Override
            public int getItemCount() {
                return photoList.size();
            }
        });
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if(swipe_count >= 5) {
                    if(mInterstitialAd != null) {
                        mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                            @Override
                            public void onAdDismissedFullScreenContent() {
                                super.onAdDismissedFullScreenContent();
                                loadInterstitialAds();swipe_count = 0;
                            }
                        });
                        mInterstitialAd.show(PhotoActivity.this);
                    } else {
                        swipe_count = swipe_count + 1;
                    }
                }
            }
        });
        viewPager.setCurrentItem(photoList.indexOf(selected_photo));
    }

    private static class PhotoView extends RecyclerView.ViewHolder {
        private final ImageView imageView;
        private final TextView like,save,wall,share;
        public PhotoView(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.img);
            like = itemView.findViewById(R.id.like);
            save = itemView.findViewById(R.id.save);
            share = itemView.findViewById(R.id.share);
            wall = itemView.findViewById(R.id.wall);
        }
    }

    private static class NativeViewHolder extends RecyclerView.ViewHolder {
        private final NativeAdView adView;
        public NativeAdView getAdView() {
            return adView;
        }
        public NativeViewHolder(View view) {
            super(view);
            adView = view.findViewById(R.id.native_ad_view);
            adView.setMediaView(adView.findViewById(R.id.media_view));
            adView.setCallToActionView(adView.findViewById(R.id.cta));
            adView.setHeadlineView(adView.findViewById(R.id.primary));
            adView.setAdvertiserView(adView.findViewById(R.id.secondary));
            adView.setStarRatingView(adView.findViewById(R.id.rating_bar));
            adView.setBodyView(adView.findViewById(R.id.body));
            adView.setIconView(adView.findViewById(R.id.icon));
        }
    }

    private void populateNativeAdView(NativeAd nativeAd, NativeAdView adView) {
        ((AppCompatTextView) Objects.requireNonNull(adView.getHeadlineView())).setText(nativeAd.getHeadline());
        ((AppCompatTextView) Objects.requireNonNull(adView.getBodyView())).setText(nativeAd.getBody());
        ((AppCompatButton) Objects.requireNonNull(adView.getCallToActionView())).setText(nativeAd.getCallToAction());
        Objects.requireNonNull(adView.getMediaView()).setMediaContent(Objects.requireNonNull(nativeAd.getMediaContent()));
        if (nativeAd.getIcon() == null) {
            Objects.requireNonNull(adView.getIconView()).setVisibility(View.INVISIBLE);
        } else {
            ((AppCompatImageView) Objects.requireNonNull(adView.getIconView())).setImageDrawable(nativeAd.getIcon().getDrawable());
            adView.getIconView().setVisibility(View.VISIBLE);
        }
        if (nativeAd.getStarRating() == null) {
            Objects.requireNonNull(adView.getStarRatingView()).setVisibility(View.INVISIBLE);
        } else {
            ((RatingBar) Objects.requireNonNull(adView.getStarRatingView())).setRating(nativeAd.getStarRating().floatValue());
            adView.getStarRatingView().setVisibility(View.VISIBLE);
        }
        if (nativeAd.getAdvertiser() == null) {
            Objects.requireNonNull(adView.getAdvertiserView()).setVisibility(View.INVISIBLE);
        } else {
            ((AppCompatTextView) Objects.requireNonNull(adView.getAdvertiserView())).setText(nativeAd.getAdvertiser());
            adView.getAdvertiserView().setVisibility(View.VISIBLE);
        }
        adView.setNativeAd(nativeAd);
    }

    private void loadInterstitialAds() {
        AdRequest adRequest = new AdRequest.Builder().build();
        InterstitialAd.load(this,getString(R.string.interstitial_id),adRequest,new InterstitialAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                super.onAdLoaded(interstitialAd);
                mInterstitialAd = interstitialAd;
            }
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                mInterstitialAd = null;
            }
        });
    }
}