package com.makeeasy.dpandstatus;

import static com.makeeasy.dpandstatus.Constant.CATEGORYARRAY;
import static com.makeeasy.dpandstatus.Constant.CATEGORY_IMAGE;
import static com.makeeasy.dpandstatus.Constant.CATEGORY_NAME;
import static com.makeeasy.dpandstatus.Constant.CATEGORY_URL;
import static com.makeeasy.dpandstatus.Constant.CID;
import static com.makeeasy.dpandstatus.Constant.OK;
import static com.makeeasy.dpandstatus.Constant.POST_COUNT;
import static com.makeeasy.dpandstatus.Constant.STATUS;
import static com.makeeasy.dpandstatus.Constant.alertBox;
import static com.makeeasy.dpandstatus.MainActivity.categoryList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.makeeasy.dpandstatus.model.Category;

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

import java.util.ArrayList;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        if(Constant.isConnected(this)) {
            loadCategoryData();
        } else {
            Constant.alertBox(this, "No Connection Found!", "RETRY", (dialogInterface, i) -> {
                dialogInterface.dismiss();loadCategoryData();
            });
        }
    }

    private void loadCategoryData() {
        categoryList = new ArrayList<>();
        Volley.newRequestQueue(this).add(new JsonObjectRequest(CATEGORY_URL,response -> {
            try {
                if(response.getString(STATUS).equalsIgnoreCase(OK)) {
                    JSONArray data = response.getJSONArray(CATEGORYARRAY);
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject obj = data.getJSONObject(i);
                        categoryList.add(new Category(obj.getString(CID),obj.getString(CATEGORY_NAME),
                                obj.getString(CATEGORY_IMAGE),obj.getString(POST_COUNT)));
                    }
                    startActivity(new Intent(SplashActivity.this,MainActivity.class));
                    finish();
                } else {
                    alertBox(this,"Something went wrong!");
                }
            } catch (JSONException e) {
                alertBox(this,e.getMessage());
            }
        }, error -> alertBox(this,error.getMessage())));
    }
}