package com.dittomart.meatsbhavan.ui;

import static com.dittomart.meatsbhavan.util.Constant.INTENT_DOMAINS;
import static com.dittomart.meatsbhavan.util.Constant.STORE_COLOR;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.dittomart.meatsbhavan.R;
import com.dittomart.meatsbhavan.api.Api;
import com.dittomart.meatsbhavan.network.RetrofitInstance;
import com.dittomart.meatsbhavan.util.CallbackWithRetry;
import com.dittomart.meatsbhavan.util.Constant;
import com.dittomart.meatsbhavan.util.Funtionality;
import com.dittomart.meatsbhavan.util.PackageVerificationListener;
import com.dittomart.meatsbhavan.util.SharePref;
import com.google.gson.Gson;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashScreenActivity extends BaseActivity {

    private static final String TAG = SplashScreenActivity.class.getSimpleName();
    long timestart;
    private ImageView screen_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        timestart = System.currentTimeMillis();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        
        // Status bar is configured in BaseActivity
        //SharePref sharePref = new SharePref(this);
        screen_iv = findViewById(R.id.screen_iv);

        Animation fade_in = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        screen_iv.setAnimation(fade_in);

        //firstverify
        if (!SharePref.getBooleanFromPref(Constant.ANLIVER_CHECKED)) {
            //if anliverChecked false then
            if (!SharePref.getBooleanFromPref(Constant.ANLIVER)) {
                // if anliver false then call for api to check ANLIVER
                Funtionality.checkAndroidPackage(this, new PackageVerificationListener() {
                    @Override
                    public void onSuccess() {
                        getSettings();
                    }

                    @Override
                    public void onFailure(String message) {
                        Toast.makeText(SplashScreenActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                //Toast.makeText(this, "getting settings...", Toast.LENGTH_SHORT).show();
                getSettings();
            }
        } else {
            //if ANLIVER(First time) checking is true then check for ANLIVER
            if (SharePref.getBooleanFromPref(Constant.ANLIVER)) {
                // if this is true then start app
                getSettings();
            } else {
                Toast.makeText(this, "Please try to install Licensed App", Toast.LENGTH_SHORT).show();
            }
        }

    }


    private void getSettings() {
        if (!SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL).equals(""))
            Constant.BASE_URL = SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL);


        Api apiService = RetrofitInstance.getRetrofitIntance().create(Api.class);
//        SharePref.setDataPref(STORE_COLOR, "#ffffff");
//        Log.d(TAG, "Preference: " + SharePref.getDataFromPref(STORE_COLOR));
//        StartApp();
        apiService.getSetting(STORE_COLOR).enqueue(new CallbackWithRetry<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                if (!response.isSuccessful()) {
                    try {
                        throw new Exception("Server error");
                    } catch (Exception e) {
                        super.onFailure(call, e);
                    }
                } else {
                    String json = new Gson().toJson(response.body());
                    try {
                        JSONObject object = new JSONObject(json.trim());
                        SharePref.setDataPref(STORE_COLOR, object.getString("value"));
                        Log.d(TAG, "Preference: " + SharePref.getDataFromPref(STORE_COLOR));
                        StartApp();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                super.onFailure(call, t);

            }
        });

        apiService.getSetting(INTENT_DOMAINS).enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                Log.d(TAG, "onResponse: Code: " + response.code() + " Successful :" + response.isSuccessful() + "Body :" + response.body());
                if (response.code() == 200) {
                    if (response.isSuccessful()) {
                        String intentDomains;
                        if (!response.body().toString().equals("")) {
                            intentDomains = response.body().toString();
                            SharePref.setDataPref(INTENT_DOMAINS, intentDomains);
                        } else
                            SharePref.setDataPref(INTENT_DOMAINS, "[]");

                    } else {
                        SharePref.setDataPref(INTENT_DOMAINS, "[]");
                    }
                } else {
                    SharePref.setDataPref(INTENT_DOMAINS, "[]");
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
                SharePref.setDataPref(INTENT_DOMAINS, "[]");
            }
        });

    }


    private void StartApp() {
        long stopTime = System.currentTimeMillis();
        long total = stopTime - timestart;
        Log.d(TAG, "Timer: " + total);
//        Toast.makeText(this,String.valueOf(total),Toast.LENGTH_SHORT).show();
        //push notification permission
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
//            Log.e("PushNotification", "not granted");
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, 102);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS);
//            }
//        } else
//            startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33 or above
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                Log.e("PushNotification", "Permission not granted");

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.POST_NOTIFICATIONS)) {
                    // Show an explanation to the user before requesting the permission
                    Log.e("PushNotification", "Show permission rationale");
                    // Display a dialog or some UI to explain why you need the permission
                }

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, 102);
            } else {
                // Permission granted, proceed to the next activity
                startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
            }
        } else {
            // No need to check for POST_NOTIFICATIONS permission on versions below Android 13
            startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
        }

    }

//    @RequiresApi(api = Build.VERSION_CODES.M)
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        Log.d(TAG, "REQUEST CODE: " + requestCode + " permission :" + Arrays.toString(permissions));
//
//        if (requestCode == 102) {
//            Log.d(TAG, "onRequestPermissionsResult: LENGTH " + grantResults.length + "  " + Arrays.toString(grantResults));
//            if (grantResults.length > 0) {
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
//                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
//                    startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
//                }
//            }
//        }
//    }
    

}

