/*
 * 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.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

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

import com.facebook.ads.AudienceNetworkAds;
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.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.messaging.FirebaseMessaging;


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.BuildConfig;
import stickeradmin.signalstickers.trending.Config.GlobalConfig;
import stickeradmin.signalstickers.trending.R;
import stickeradmin.signalstickers.trending.stickermaker.DataArchiver;
import stickeradmin.signalstickers.trending.stickermaker.StickerBook;


public class MainActivity extends BaseActivity {

    private static final String TAG = "StickerPackList";
    public static Context context;
    private static RecyclerView packRecyclerView;
    private static StickerPackListAdapter allStickerPacksListAdapter;

    ArrayList<StickerPack> stickerPackList;
    AlertDialog alertDialog;
    boolean FoundNewPack = false;
    boolean IsPackLoaded = false;
    boolean IsThreadRunning = false;
    private GridLayoutManager packLayoutManager;
    private TextView info_message;
    private JSONArray cloudArray;
    private ProgressDialog mProgressDialog;
    private String _Value = "";
    private AdView mAdView;
    private LinearLayout fb_banner_container;
    com.facebook.ads.AdView fb_AdView;

    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 {
                    MainActivity.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();
            }
        }
    };

    public static ArrayList<StickerPack> reverse(ArrayList<StickerPack> list) {
        if (list.size() > 1) {
            StickerPack value = list.remove(0);
            reverse(list);
            list.add(value);
        }
        return list;
    }

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

    @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;
    }

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

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

        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);


        AudienceNetworkAds.initialize(this);

        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 (Intent.ACTION_SEND.equals(getIntent().getAction())) {
            Bundle extras = getIntent().getExtras();
            if (extras.containsKey(Intent.EXTRA_STREAM)) {
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                if (uri != null) {
                    //DataArchiver.importZipFileToStickerPack(uri, StickerPackListActivity.this);
                }
            }
        }

        try
        {
            if (getIntent().getExtras() != null) {
                for (String key : getIntent().getExtras().keySet()) {
                    String value = getIntent().getExtras().getString(key);
                    if (key.equals("STICKERID")) {
                        _Value = value;
                    }
                }
            }
        }
        catch (Exception ex){}

        if (!_Value.equals("")) {
            alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setMessage("Please Wait...");
            alertDialog.show();
        }
    }

    private void LoadBannerAd()
    {
        AdRequest adRequest = new AdRequest.Builder().build();
        LinearLayout adContainer = (LinearLayout) findViewById(R.id.fb_banner_container);
        if( getResources().getString(R.string.Ads).equals("ADMOB") ){
            mAdView.setAdListener(new AdListener() {
                @Override
                public void onAdFailedToLoad(int errorCode) {
                }
            });
            mAdView.loadAd(adRequest);
            adContainer.setVisibility(View.GONE);
        }
        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_1), com.facebook.ads.AdSize.BANNER_HEIGHT_50);
            adContainer.addView(fb_AdView);
            fb_AdView.loadAd();
        }
    }

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

    private void NowLoadStickerPack() {
        stickerPackList = StickerBook.getAllStickerPacks();
        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);
    }

    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");
                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)) {
                    _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;
            try {
                _cPack = cloudArray.getJSONObject(i);
                cIdentifier = _cPack.getString("identifier");
                cName = _cPack.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            StickerPack pack = StickerBook.getStickerPackById(cIdentifier);
            if (pack.getCount() == 0 && (_cPack != null)) {
                info_message.setText("Loading Sticker  \" " + cName + " \" - ");
                if (IsThreadRunning == false) {
                    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();
            LoadBannerAd();

            if (!_Value.equals("")) {
                try {
                    alertDialog.dismiss();
                } catch (Exception ex) {
                }
                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);
            }
        }
    }

    public void showStickerPackList(List<StickerPack> stickerPackList) {
        try {
            allStickerPacksListAdapter = new StickerPackListAdapter(stickerPackList, onAddButtonClickedListener);
            packRecyclerView.setAdapter(allStickerPacksListAdapter);
            packLayoutManager = new GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false);

            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                packLayoutManager = new GridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);
                //Toast.makeText(this, "I am in Landscape Mode", Toast.LENGTH_SHORT).show();
            } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                packLayoutManager = new GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false);
                //Toast.makeText(this, "I am in portrait Mode", Toast.LENGTH_SHORT).show();
            }
            packRecyclerView.setLayoutManager(packLayoutManager);
            packRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(this::recalculateColumnCount);
        } catch (Exception ex) {
        }
    }

    private void recalculateColumnCount() {

    }

    @Override
    public void onDestroy() {
        try {
            DataArchiver.writeStickerBookJSON(StickerBook.getAllStickerPacks(), this);
        } catch (Exception ex) {
            Log.d("ERROR", ex.getMessage());
        }
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        DataArchiver.writeStickerBookJSON(StickerBook.getAllStickerPacks(), this);
    }

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



    class DownloadOnlySets extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... f_url) {
            StickerPack sp;
            String packName = "";
            String packpublisher = "";
            String IsAnimated = "false";
            try {
                JSONObject sticker_pack = new JSONObject(f_url[0]);
                JSONArray arrStickers = sticker_pack.getJSONArray("stickers");
                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");
                try
                {
                    IsAnimated = sticker_pack.getString("IsAnimated");
                }
                catch (Exception ex){}

                String 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,
                        IsAnimated,
                        MainActivity.context);

                for (int i = 0; i < arrStickers.length(); i++) {
                    JSONObject currentSticker = arrStickers.getJSONObject(i);
                    String stickerName = currentSticker.getString("image_file");
                    if(IsAnimated.equals("true"))
                    {
                        Uri uri = Uri.parse(GlobalConfig.API_Base_Url + "/" + identifier + "_small/" + stickerName + ".png");
                        sp.addSticker(uri, MainActivity.context);
                    }
                    else
                    {
                        Uri uri = Uri.parse(GlobalConfig.API_Base_Url + "/" + identifier + "_small/" + stickerName + ".webp");
                        sp.addSticker(uri, MainActivity.context);
                    }

                }
                StickerBook.addStickerPackExisting(sp);

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

        @Override
        protected void onPostExecute(String result) {
            CompaireStickerSets();
        }
    }

    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("SHUBHCODE", firstObject.toString());
                cloudArray = jArray;
                CompaireStickerSets();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
