package com.app.rewardapp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.adcolony.sdk.AdColony;
import com.adcolony.sdk.AdColonyAppOptions;
import com.app.rewardapp.BuildConfig;
import com.app.rewardapp.R;
import com.app.rewardapp.Responsemodel.CallbackResp;
import com.app.rewardapp.Responsemodel.ConfigResp;
import com.app.rewardapp.restApi.ApiClient;
import com.app.rewardapp.restApi.ApiInterface;
import com.app.rewardapp.adsManager.AdImp;
import static com.ads.androidsdk.sdk.util.Api.getBaseUrl;
import static com.ads.androidsdk.sdk.util.Tool.encrypt;
import static com.ads.androidsdk.sdk.util.Tool.isConnected;
import static com.app.rewardapp.util.Const.getAU;
import static com.app.rewardapp.util.Constant_Api.APi;
import com.app.rewardapp.util.Constant_Api;
import com.app.rewardapp.util.Fun;
import com.app.rewardapp.util.Session;
import com.applovin.sdk.AppLovinMediationProvider;
import com.applovin.sdk.AppLovinPrivacySettings;
import com.applovin.sdk.AppLovinSdk;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.AdapterStatus;
import com.google.firebase.FirebaseApp;
import com.ornach.nobobutton.NoboButton;
import com.startapp.sdk.adsbase.StartAppAd;
import com.startapp.sdk.adsbase.StartAppSDK;
import com.unity3d.ads.IUnityAdsInitializationListener;
import com.unity3d.ads.UnityAds;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.app.rewardapp.util.Constant_Api.App;
import static com.app.rewardapp.util.Constant_Api.isVpn;
import static com.app.rewardapp.util.Fun.data;

import java.util.Locale;
import java.util.Map;

public class Splash extends AppCompatActivity implements AdImp {
    Session session;
    AlertDialog alertDialog, dialog;
    Activity activity;
    CountDownTimer count;
    public static final String TAG="Splash Activity : ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        FirebaseApp.initializeApp(this);
        activity = this;

        session = new Session(this);
        alertDialog = Fun.Alert(this);

        updatelang();

        dialog = new AlertDialog.Builder(this).setView(LayoutInflater.from(this).inflate(R.layout.layout_dialog, null)).create();
        dialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        dialog.getWindow().setWindowAnimations(R.style.Dialoganimation);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        if (isConnected(this)) {
            loadConfig();
        } else {
            showAlert(getString(R.string.no_internet));
        }


    }

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

    void showAlert(String msg) {
        alertDialog.show();
        TextView tv = alertDialog.findViewById(R.id.txt);
        tv.setText(msg);
        alertDialog.findViewById(R.id.close).setOnClickListener(v -> {
            alertDialog.dismiss();
        });
    }

    private void loadConfigSetting() {
        Call<ConfigResp> call = ApiClient.getClient(this).create(ApiInterface.class).getConfig();
        call.enqueue(new Callback<ConfigResp>() {
            @Override
            public void onResponse(Call<ConfigResp> call, Response<ConfigResp> response) {
                if (response.isSuccessful() && response.body().getSuccess() != 0) {
                    App = response.body();
                    isVpn=response.body().isVpn();
                    prepareAd();

                    if (response.body().getData().get(0).isUp_status()) {
                        if (response.body().getData().get(0).getUp_mode().equals(Constant_Api.UPDATE)) {
                            if (BuildConfig.VERSION_CODE < response.body().getData().get(0).getUp_version()) {
                                show(response.body().getData().get(0).getUp_msg(), "update", response.body().getData().get(0).getUp_link(), response.body().getData().get(0).isUp_btn());
                            } else {
                                doTask();
                            }
                        } else {
                            show(response.body().getData().get(0).getUp_msg(), Constant_Api.MAINTENANCE, "", false);
                        }
                    } else {
                        doTask();
                    }
                } else {
                    showAlert(response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ConfigResp> call, Throwable t) {
            }
        });
    }

    private void prepareAd() {
        if(!getString(R.string.ADMOB_APPID).equals("ca-app-pub-3940256099942544~3347511713")){
            MobileAds.initialize(activity, initializationStatus -> {
                Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
                for (String adapterClass : statusMap.keySet()) {
                    AdapterStatus adapterStatus = statusMap.get(adapterClass);
                    assert adapterStatus != null;
                    Log.d(TAG, String.format("Adapter name: %s, Description: %s, Latency: %d", adapterClass, adapterStatus.getDescription(), adapterStatus.getLatency()));
                }
            });
        }

        if(App.getData().get(0).getStartappid()!=null){
            StartAppSDK.init(activity,App.getData().get(0).getStartappid(), false);
            StartAppAd.disableSplash();
            StartAppSDK.setUserConsent(activity, "pas", System.currentTimeMillis(), true);
        }

        if(getString(R.string.APPLOVIN_SDK_KEY)!=null){
            AppLovinPrivacySettings.setIsAgeRestrictedUser( false,activity);
            AppLovinPrivacySettings.setDoNotSell( true,activity);
            AppLovinSdk.getInstance(activity).setMediationProvider(AppLovinMediationProvider.MAX);
            AppLovinSdk.getInstance(activity).initializeSdk(config -> {
            });
        }

        if(App.getData().get(0).getUnityGameid()!=null){
            UnityAds.initialize(activity.getApplicationContext(),App.getData().get(0).getUnityGameid(), false, new IUnityAdsInitializationListener() {
                @Override
                public void onInitializationComplete() {
                    Log.d(TAG, "Unity Ads Initialization Complete with ID : " +  App.getData().get(0).getUnityGameid());
                }
                @Override
                public void onInitializationFailed(UnityAds.UnityAdsInitializationError error, String message) {
                    Log.d(TAG, "Unity Ads Initialization Failed: [" + error + "] " + message);
                }
            });
        }

        if( App.getData().get(0).getAdcolonyAppID()!=null){
            AdColonyAppOptions appOptions =  new AdColonyAppOptions().setGDPRConsentString("1")
                    .setKeepScreenOn(true).setGDPRRequired(true);
            AdColony.configure(activity, appOptions, App.getData().get(0).getAdcolonyAppID());
        }

    }

    private void updatelang() {
        if (session.getData(session.SELECTED_LANGUAGE) != null) {
            if (session.getData(session.SELECTED_LANGUAGE).equals("hi")) {
                setLocale("hi");
            } else if (session.getData(session.SELECTED_LANGUAGE).equals("tr")) {
                setLocale("tr");
            } else if (session.getData(session.SELECTED_LANGUAGE).equals("en")) {
                setLocale("en");
            } else if (session.getData(session.SELECTED_LANGUAGE).equals("es")) {
                setLocale("es");
            } else if (session.getData(session.SELECTED_LANGUAGE).equals("ben")) {
                setLocale("ben");
            }
        }
    }

    private void doTask() {
        if (session.getBoolean(session.LOGIN)) {
            reqLogin(session.getData(session.EMAIL),session.getData(session.PASSWORD),session.Auth());
        } else {
            if (!session.getBoolean(session.FIRSTTIME)) {
                startActivity(new Intent(Splash.this, IntroActivity.class));
            } else {
                startActivity(new Intent(Splash.this, FrontLogin.class));
            }
        }
    }

    private void loadConfig() {
        APi = getBaseUrl(Splash.this,getAU());
        loadConfigSetting();
    }

    private void reqLogin(String email, String password,String randomNumber) {
        Call<CallbackResp> login = ApiClient.getClient(this).create(ApiInterface.class).ApiUser(data("", email, password, randomNumber, "", "", 1, 0, session.Auth()));
        login.enqueue(new Callback<CallbackResp>() {
            @Override
            public void onResponse(Call<CallbackResp> call, Response<CallbackResp> response) {
                if (response.isSuccessful() && response.body().getCode() == 201) {
                    session.saveUserData(response.body().getUser().getGoogle(),
                            response.body().getUser().getEmail(),
                            response.body().getUser().getPhone(),
                            response.body().getUser().getName(),
                            password,
                            response.body().getUser().getRefferalId(),
                            response.body().getUser().getFrom_refer(),
                            Constant_Api.AUTH + encrypt(response.body().getWkdWMmFXTmxYMmxr()).replace(response.body().getUser().getToken(), ""));
                    session.setData(session.emailVerified, response.body().getUser().getEmailVerified());
                    session.setIntData(session.WALLET, response.body().getUser().getBalance());
                    session.setBoolean(session.LOGIN, true);
                    Intent intent = new Intent(Splash.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(Splash.this, FrontLogin.class);
                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(Call<CallbackResp> call, Throwable t) {
                Log.e("splash", "onFailure: " + t.getMessage());
            }
        });
    }
    void show(String msg, String type, String url, boolean skip) {
        dialog.show();
        TextView tv, congrats;
        Button btn;
        NoboButton skipbtn;
        tv = dialog.findViewById(R.id.txt);
        congrats = dialog.findViewById(R.id.congrts);
        tv.setText(msg);
        btn = dialog.findViewById(R.id.yes);
        skipbtn = dialog.findViewById(R.id.no);
        skipbtn.setText(getString(R.string.skip));
        ImageView imageView = dialog.findViewById(R.id.img);

        if (type.equals(Constant_Api.MAINTENANCE)) {
            btn.setVisibility(View.GONE);
            imageView.setImageResource(R.drawable.ic_baseline_cloud_off_24);
            congrats.setText(getString(R.string.maintenance));
            congrats.setTextColor(getResources().getColor(R.color.red));
            skipbtn.setText(getString(R.string.close));
        } else {
            imageView.setImageResource(R.drawable.ic_baseline_autorenew_24);
            congrats.setText(getString(R.string.update_available));
            btn.setVisibility(View.VISIBLE);
            btn.setText(getString(R.string.update));
        }
        if (!skip) {
            skipbtn.setVisibility(View.GONE);
        }
        skipbtn.setOnClickListener(view -> {
            if (type.equals(Constant_Api.MAINTENANCE)) {
                dialog.dismiss();
            } else {
                doTask();
            }
        });

        btn.setOnClickListener(view -> {
            if (type.equals(Constant_Api.MAINTENANCE)) {
                dialog.dismiss();
            } else {
                openUrl(url);
            }
        });
    }
    private void openUrl(String url) {
        try {
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                url = "http://" + url;
            }
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
        } catch (Exception e) {
        }
    }


    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
    }

}
