

/*
 * Copyright (c) WhatsApp Inc. and its affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

package stickeradmin.signalstickers.trending.stickermaker.WhatsAppBasedCode;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AudienceNetworkAds;
import com.facebook.ads.InterstitialAdListener;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

import org.json.JSONArray;

import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import stickeradmin.signalstickers.trending.BuildConfig;
import stickeradmin.signalstickers.trending.Config.GlobalConfig;
import stickeradmin.signalstickers.trending.R;
import stickeradmin.signalstickers.trending.stickermaker.DataArchiver;
import stickeradmin.signalstickers.trending.stickermaker.StickerBook;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class StickerPackDetailsActivity extends BaseActivity {

    /**
     * Do not change below values of below 3 lines as this is also used by WhatsApp
     */
    public static final String EXTRA_STICKER_PACK_ID = "sticker_pack_id";
    public static final String EXTRA_STICKER_PACK_AUTHORITY = "sticker_pack_authority";
    public static final String EXTRA_STICKER_PACK_NAME = "sticker_pack_name";

    public static final int ADD_PACK = 200;
    public static final String EXTRA_SHOW_UP_BUTTON = "show_up_button";
    public static final String EXTRA_STICKER_PACK_DATA = "sticker_pack";

    private RecyclerView recyclerView;
    private GridLayoutManager layoutManager;
    private StickerPreviewAdapter stickerPreviewAdapter;
    private int numColumns;
    private StickerPack stickerPack;
    private View divider;
    private InterstitialAd mInterstitialAd;
    private FrameLayout add_to_signal_button;
    private com.facebook.ads.InterstitialAd FBinterstitialAd;
    private AdView mAdView;
    com.facebook.ads.AdView fb_AdView;

    class DownloadFileFromURL extends AsyncTask<String, Integer, String>
    {
        @Override
        protected String doInBackground(String... strings) {
            try
            {
                for (int i = 0; i < stickerPack.getStickerCount(); i++)
                {
                    String stickerName=String.format("%02d", i +1);
                    Log.d("stickerName",stickerName);
                    Uri uri = Uri.parse( GlobalConfig.API_Base_Url + "/"+ stickerPack.getIdentifier() +"_small/"+ stickerName +".webp");
                    stickerPack.addSticker(uri, StickerPackListActivity2.context);
                }
            }
            catch(Exception ex)
            {
                Log.d("stickerName", ex.getMessage() );
            }

            return null;
        }
        @Override
        protected void onPostExecute(String result){
            stickerPreviewAdapter = new StickerPreviewAdapter(getLayoutInflater(), R.drawable.sticker_error, getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size), getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_padding), stickerPack);
            recyclerView.setAdapter(stickerPreviewAdapter);
        }
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loader_sticker_pack_details);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        add_to_signal_button=findViewById(R.id.add_to_signal_button);

        AudienceNetworkAds.initialize(this);

        mAdView = findViewById(R.id.adView_2);
        LinearLayout adContainer = (LinearLayout) findViewById(R.id.fb_banner_container_detail);

        if( getResources().getString(R.string.Ads).equals("ADMOB") )
        {
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.setAdListener(new AdListener(){
                @Override
                public void onAdFailedToLoad(int errorCode) {
                    Log.d("TAG", "The Banner wasn't loaded yet.---LDR");
                }
            });
            mAdView.loadAd(adRequest);
            adContainer.setVisibility(View.GONE);

            mInterstitialAd = new InterstitialAd(this);
            mInterstitialAd.setAdUnitId( getResources().getString(R.string.AdmobInterstitial) );
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
        else if (getResources().getString(R.string.Ads).equals("FACEBOOK")){
            mAdView.setVisibility(View.GONE);
            fb_AdView=new com.facebook.ads.AdView(this, getResources().getString(R.string.FB_Banner_Ad_PlacemaneId_2), com.facebook.ads.AdSize.BANNER_HEIGHT_50);
            adContainer.addView(fb_AdView);
            fb_AdView.loadAd();

            FBinterstitialAd = new com.facebook.ads.InterstitialAd(this, getResources().getString(R.string.FB_Interstitial_Ad_PlacemaneId));

            InterstitialAdListener interstitialAdListener = new InterstitialAdListener(){

                @Override
                public void onError(Ad ad, AdError adError) {

                }

                @Override
                public void onAdLoaded(Ad ad) {

                }

                @Override
                public void onAdClicked(Ad ad) {

                }

                @Override
                public void onLoggingImpression(Ad ad) {

                }

                @Override
                public void onInterstitialDisplayed(Ad ad) {

                }

                @Override
                public void onInterstitialDismissed(Ad ad) {

                }
            };

            FBinterstitialAd.loadAd(
                    FBinterstitialAd.buildLoadAdConfig()
                            .withAdListener(interstitialAdListener)
                            .build());

        }


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(R.layout.activity_progress);



        boolean showUpButton = getIntent().getBooleanExtra(EXTRA_SHOW_UP_BUTTON, false);
        stickerPack = StickerBook.getStickerPackById(getIntent().getStringExtra(EXTRA_STICKER_PACK_DATA));
        TextView packNameTextView = findViewById(R.id.pack_name);
        TextView packPublisherTextView = findViewById(R.id.author);
        ImageView packTrayIcon = findViewById(R.id.tray_image);



        layoutManager = new GridLayoutManager(this, 1);
        recyclerView = findViewById(R.id.sticker_list);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(pageLayoutListener);
        recyclerView.addOnScrollListener(dividerScrollListener);
        divider = findViewById(R.id.divider);


        if (stickerPreviewAdapter == null) {
            if(stickerPack.getCount() < stickerPack.getStickerCount() )
            {
                Log.d("stickerName","Need Loading Sticker");
                new DownloadFileFromURL().execute();
            }
            else
            {
                Log.d("stickerName","Pack Found");
                stickerPreviewAdapter = new StickerPreviewAdapter(getLayoutInflater(), R.drawable.sticker_error, getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size), getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_padding), stickerPack);
                recyclerView.setAdapter(stickerPreviewAdapter);
            }

        }
        packNameTextView.setText(stickerPack.name);
        packPublisherTextView.setText(stickerPack.publisher);


        Glide.with(this).load(R.drawable.loading).into(packTrayIcon);

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.loading);


        Glide.with(this).load(
                GlobalConfig.API_Base_Url +"/"+ stickerPack.getIdentifier() + "_small/01.webp"
        )
                .apply(requestOptions)
                .into(packTrayIcon);

        add_to_signal_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowInterstitial();
                String URL=stickerPack.getSignalStickerPackURL();
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
                startActivity(browserIntent);
            }
        });


        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(showUpButton);
            getSupportActionBar().setTitle(showUpButton ? R.string.title_activity_sticker_pack_details_multiple_pack : R.string.title_activity_sticker_pack_details_single_pack);
        }
    }
    private void ShowInterstitial(){
// else {
//            Log.d("TAG", "The interstitial wasn't loaded yet.---LDR");
//        }

        if( getResources().getString(R.string.Ads).equals("ADMOB") ){
                    if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
        }
        else if (getResources().getString(R.string.Ads).equals("FACEBOOK")){
            if(FBinterstitialAd.isAdLoaded()){
                FBinterstitialAd.show();
            }
        }
    }




    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return super.onCreateOptionsMenu(menu);
    }



    private final ViewTreeObserver.OnGlobalLayoutListener pageLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            setNumColumns(recyclerView.getWidth() / recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size));
        }
    };

    private void setNumColumns(int numColumns) {
        if (this.numColumns != numColumns) {
            layoutManager.setSpanCount(numColumns);
            this.numColumns = numColumns;
            if (stickerPreviewAdapter != null) {
                stickerPreviewAdapter.notifyDataSetChanged();
            }
        }
    }

    private final RecyclerView.OnScrollListener dividerScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull final RecyclerView recyclerView, final int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            updateDivider(recyclerView);
        }

        @Override
        public void onScrolled(@NonNull final RecyclerView recyclerView, final int dx, final int dy) {
            super.onScrolled(recyclerView, dx, dy);
            updateDivider(recyclerView);
        }

        private void updateDivider(RecyclerView recyclerView) {
            boolean showDivider = recyclerView.computeVerticalScrollOffset() > 0;
            if (divider != null) {
                divider.setVisibility(showDivider ? View.VISIBLE : View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }



}
