/*
 * 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.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.facebook.drawee.backends.pipeline.Fresco;

import com.facebook.soloader.SoLoader;
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.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.firebase.messaging.FirebaseMessaging;

import stickeradmin.signalstickers.trending.Config.GlobalConfig;

import stickeradmin.signalstickers.trending.BuildConfig;
import stickeradmin.signalstickers.trending.R;
import stickeradmin.signalstickers.trending.stickermaker.DataArchiver;
import stickeradmin.signalstickers.trending.stickermaker.StickerBook;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import stickeradmin.signalstickers.trending.stickermaker.NewUserIntroActivity;


public class StickerPackListActivity2 extends BaseActivity {
    private static final int STICKER_PREVIEW_DISPLAY_LIMIT = 5;
   private static final String TAG = "StickerPackList";
    private LinearLayoutManager packLayoutManager;
    private static RecyclerView packRecyclerView;
    private static StickerPackListAdapter allStickerPacksListAdapter;

    ArrayList<StickerPack> stickerPackList;
    public static Context context;
    private TextView info_message;
    private JSONArray cloudArray;
    private ProgressDialog mProgressDialog;
    private String _Value="";
    private AdView mAdView;
    AlertDialog alertDialog;
    boolean FoundNewPack=false;
    boolean IsPackLoaded=false;
    boolean IsFirst=false;

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

    @Override
    public void onBackPressed(){
        moveTaskToBack(true);
    }


    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.loader_activity_sticker_pack_list);

        Fresco.initialize( this );
        StickerBook.init(this);
        FirebaseMessaging.getInstance().setAutoInitEnabled(true);

        FirebaseMessaging.getInstance().subscribeToTopic("toAll");
        context = getApplicationContext();
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });



        mAdView = findViewById(R.id.adView_1);
        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);

        SoLoader.init( this , /* native exopackage */ false);

        info_message=findViewById(R.id.info_message);
        info_message.setText("Checking latest stickers...");

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Loading Stickers..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(false);

        new FetchNewData().execute();

        packRecyclerView = findViewById(R.id.sticker_pack_list);
        loadStickerPack();



        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                String value = getIntent().getExtras().getString(key);
                Log.d("surajfirebase", "Key: " + key + " Value: " + value);
                if(key .equals("STICKERID"))
                {
                    _Value=value;
                }
            }
        }

        if( ! _Value.equals("") )
        {
            Log.d("surajfirebase", "New StickerId=" + _Value);
            alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setMessage("Please Wait...");
            alertDialog.show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.action_pp: {
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Privacy Policy");
                WebView wv = new WebView(this);
                wv.loadUrl("file:///android_asset/PrivacyPolicy.html");
                wv.setWebViewClient(new WebViewClient());
                alert.setView(wv);
                alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
                alert.show();
                return true;
            }
            case R.id.action_share:
            {
                Intent _myIntent =new Intent(Intent.ACTION_SEND);
                _myIntent.setType("text/plain");
                String ShareBody="Hi \nPlease check this Awesome Application. '"+ getResources().getString(R.string.app_name) +"'\nYou'll love it. \n\nhttps://play.google.com/store/apps/details?id=" + getPackageName();
                String ShareSub="Subject";
                _myIntent.putExtra(Intent.EXTRA_SUBJECT,ShareSub);
                _myIntent.putExtra(Intent.EXTRA_TEXT,ShareBody);
                startActivity( Intent.createChooser(_myIntent ,"Share using") );
                return true;
            }
        }
        return true;
    }

    private void loadStickerPack()
    {
        if(IsPackLoaded==false)
        {
            NowLoadStickerPack();
        }
       else if(FoundNewPack==true)
        {
            FoundNewPack=false;
            NowLoadStickerPack();
        }
    }


    private void NowLoadStickerPack()
    {
        stickerPackList = StickerBook.getAllStickerPacks();//getIntent().getParcelableArrayListExtra( EXTRA_STICKER_PACK_LIST_DATA);

        if(stickerPackList.size()==0)
        {
            IsFirst=true;
        }

        Collections.sort(stickerPackList, new Comparator<StickerPack>(){
            public int compare(StickerPack obj1, StickerPack obj2) {
                return Integer.valueOf(obj2.getIdentifier()).compareTo(Integer.valueOf(obj1.getIdentifier())); // To compare integer values
            }
        });
        IsPackLoaded=true;
        showStickerPackList(  stickerPackList  );
    }
    public static ArrayList<StickerPack> reverse(ArrayList<StickerPack> list) {
        if(list.size() > 1) {
            StickerPack value = list.remove(0);
            reverse(list);
            list.add(value);
        }
        return list;
    }





    class DownloadOnlySets extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... f_url){

            StickerPack sp;
            String packName="";
            String packpublisher="";
            String SignalStickerPackURL="";
            try {
                JSONObject sticker_pack = new JSONObject(f_url[0]);
                JSONArray arrStickers=sticker_pack .getJSONArray("stickers");
                Log.d("arrStickers",arrStickers.toString());
                String identifier = sticker_pack.getString("identifier");
                String tray_image_file = sticker_pack.getString("tray_image_file");
                packName= sticker_pack.getString("name");
                packpublisher= sticker_pack.getString("publisher");
                SignalStickerPackURL= sticker_pack.getString("SignalStickerPackURL");
                Uri u= Uri.parse(GlobalConfig.API_Base_Url + identifier + "/" + tray_image_file );
                    sp = new StickerPack(
                            identifier,
                            packName,
                            packpublisher,
                            u,
                            "",
                            "",
                            "",
                            "",
                            SignalStickerPackURL,
                            "false",
                            StickerPackListActivity2.context);

                    StickerBook.addStickerPackExisting(sp);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result){
            CompaireStickerSets();
        }
    }
    boolean  IsThreadRunning=false;
    class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... f_url) {
            try {
                IsThreadRunning=true;
                JSONObject sticker_pack = new JSONObject(f_url[0]);
                JSONArray arrStickers=sticker_pack .getJSONArray("stickers");
                String identifier = sticker_pack.getString("identifier");
                StickerPack stickerPack = StickerBook.getStickerPackById(identifier);

                for (int i = 0; i < arrStickers.length(); i++){
                    JSONObject currentSticker = arrStickers.getJSONObject(i);
                    String stickerName = currentSticker.getString("image_file");
                    Log.d("SURAJ","Downloading -" + stickerName );

                    Uri uri = Uri.parse( GlobalConfig.API_Base_Url + "/"+ identifier +"_small/"+ stickerName +".webp");
                    stickerPack.addSticker(uri, StickerPackListActivity2.context);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(String result){
            loadStickerPack();
            Log.d("identifier","CompaireStickerSets"  );
            IsThreadRunning=false;
            CeckForSticrItems();
        }
    }

    private class FetchNewData extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params){
            HttpURLConnection urlConnection = null;
            StringBuilder result = new StringBuilder();
            try {
                URL url = new URL( GlobalConfig.API_Content_Url );
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

            }catch( Exception e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }


            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            Log.w(TAG,result);
            try {
                JSONObject jObject = new JSONObject(result);
                JSONArray jArray = jObject.getJSONArray("sticker_packs");
                JSONObject firstObject = jArray.getJSONObject(0);
                Log.d("SURAJ",firstObject.toString());
                //info_message.setText("HttpDont - Length= " + jArray.length());
                cloudArray=jArray;
                CompaireStickerSets();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    private void CompaireStickerSets(){

        boolean foundDiffrance=false;
        for(int i=0;i < cloudArray.length();i++){
            JSONObject _cPack= null;
            String cIdentifier=null;
            String cName=null;
            boolean _found=false;
            try {
                _cPack = cloudArray.getJSONObject(i);
                cIdentifier= _cPack.getString("identifier");
                Log.d("SURAJ","Check identifier - " + cIdentifier  );
                cName=_cPack.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int a=0; a< stickerPackList.size();a++ ){
                StickerPack pack= stickerPackList.get(a);
                    String pIdentifier=pack.identifier;
                    if( cIdentifier.equals(pIdentifier) ){
                        Log.d("SURAJ","found identifier - " + cIdentifier  );
                        _found=true;
                    }
            }
            if( _found ==false && ( _cPack !=null ) ){
                info_message.setText("Loading Sticker  \" " + cName +" \" - ");

                new DownloadOnlySets().execute(_cPack.toString());
                FoundNewPack=true;

                i=cloudArray.length();
                foundDiffrance=true;
            }
        }
        if(foundDiffrance==false){
            info_message.setText("Download Done !");


            loadStickerPack();

            CeckForSticrItems();
        }
    }

    private void CeckForSticrItems(){
        boolean foundDiffrance=false;
        for(int i=0;i < cloudArray.length();i++){
            JSONObject _cPack= null;
            String cIdentifier=null;
            String cName=null;
            boolean _found=false;
            try {
                _cPack = cloudArray.getJSONObject(i);
                cIdentifier= _cPack.getString("identifier");
                cName=_cPack.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }

                StickerPack pack= StickerBook.getStickerPackById( cIdentifier );
                String pIdentifier=pack.identifier;


            if( pack.getCount() ==0 && ( _cPack !=null ) ){
                info_message.setText("Loading Sticker  \" " + cName +" \" - ");
                if(IsThreadRunning==false)
                {
                    new DownloadFileFromURL().execute(_cPack.toString());
                    i=cloudArray.length();
                    foundDiffrance=true;
                }
            }
        }
        if(foundDiffrance==false){
            info_message.setText("Download Done !");


            for(int a=0; a< stickerPackList.size();a++ )
            {
                String cIdentifier=null;
                boolean _found=false;
                StickerPack pack= stickerPackList.get(a);
                String pIdentifier=pack.getIdentifier();
                for(int i=0;i < cloudArray.length();i++)
                {
                    try
                    {
                        JSONObject _cPack= null;
                        _cPack = cloudArray.getJSONObject(i);
                        cIdentifier= _cPack.getString("identifier");
                        if( cIdentifier.equals(pIdentifier) ){
                            _found=true;
                        }
                    }
                    catch (Exception ex)
                    {}
                }
                if( _found ==false)
                {
                    pack.setRemove(true);
                }
            }

            loadStickerPack();

            info_message.setVisibility(View.GONE);
            mProgressDialog.hide();

            if(!_Value.equals(""))
            {
                try {
                    alertDialog.dismiss();
                }
                catch (Exception ex)
                {}
                Log.d("surajfirebase","_Value="+ _Value);
                StickerPack _pack=StickerBook.getStickerPackById(_Value);
                _Value="";
                Intent intent = new Intent(this, StickerPackDetailsActivity.class);
                intent.putExtra(StickerPackDetailsActivity.EXTRA_SHOW_UP_BUTTON, true);
                intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_DATA, _pack.identifier);
                this.startActivity(intent);

            }
            else
            {
                if(IsFirst==true)
                {
                    Intent intent2 = getIntent();
                    finish();
                    startActivity(intent2);
                }
            }
        }
    }


    public void showStickerPackList(List<StickerPack> stickerPackList) {
        try{
            allStickerPacksListAdapter = new StickerPackListAdapter(stickerPackList, onAddButtonClickedListener);
            packRecyclerView.setAdapter(allStickerPacksListAdapter);
            packLayoutManager = new LinearLayoutManager(context);
            packLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(
                    packRecyclerView.getContext(),
                    packLayoutManager.getOrientation()
            );
            packRecyclerView.setLayoutManager(packLayoutManager);
            packRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(this::recalculateColumnCount);
        }
        catch(Exception ex){}
    }

    private StickerPackListAdapter.OnAddButtonClickedListener onAddButtonClickedListener = new StickerPackListAdapter.OnAddButtonClickedListener() {
        @Override
        public void onAddButtonClicked(StickerPack pack) {
            if(pack.getStickers().size()>=3) {
                Intent intent = new Intent();
                intent.setAction("com.whatsapp.intent.action.ENABLE_STICKER_PACK");
                intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_ID, pack.identifier);
                intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_AUTHORITY, BuildConfig.CONTENT_PROVIDER_AUTHORITY2);
                intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_NAME, pack.name);
                try {
                    StickerPackListActivity2.this.startActivityForResult(intent, StickerPackDetailsActivity.ADD_PACK);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(context, R.string.error_adding_sticker_pack, Toast.LENGTH_LONG).show();
                }
            } else {
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).create();
                alertDialog.setTitle("Invalid Action");
                alertDialog.setMessage("In order to be applied to WhatsApp, the sticker pack must have at least 3 stickers. Please add more stickers first.");
                alertDialog.show();
            }
        }
    };

    private void recalculateColumnCount() {
        final int previewSize = getResources().getDimensionPixelSize(R.dimen.sticker_pack_list_item_preview_image_size);
        int firstVisibleItemPosition = packLayoutManager.findFirstVisibleItemPosition();
        StickerPackListItemViewHolder viewHolder = (StickerPackListItemViewHolder) packRecyclerView.findViewHolderForAdapterPosition(firstVisibleItemPosition);
        if (viewHolder != null) {
            final int max = Math.max(viewHolder.imageRowView.getMeasuredWidth() / previewSize, 1);
            int numColumns = Math.min(STICKER_PREVIEW_DISPLAY_LIMIT, max);
            allStickerPacksListAdapter.setMaxNumberOfStickersInARow(numColumns);
        }
    }

    @Override
    public void onDestroy() {
        try{
            DataArchiver.writeStickerBookJSON(StickerBook.getAllStickerPacks(), this);
        }
        catch(Exception ex){

            Log.d("ERROR",ex.getMessage());

        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        if(stickerPackList.size() >0)
        {
            new FetchNewData().execute();
        }
        super.onResume();
    }






}
