package w.soulofpluto.posstock;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.Logout;

 /*
 Create by Ramesh Babu
 */

 //9182811074

 public class HomeActivity extends AppCompatActivity {
     Toolbar home_toolbar;
     static PreferenceManager preferenceManager;
     TextView version;
     ArrayList<String> arrayList;
     RecyclerView recyclerView;

     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState){
        setContentView(R.layout.activity_home);
        home_toolbar      = findViewById(R.id.home_toolbar);
        version           = findViewById(R.id.version);
        recyclerView      = findViewById(R.id.menu_list);
        preferenceManager = new PreferenceManager(this);
        setSupportActionBar(home_toolbar);
        getSupportActionBar().setTitle( Html.fromHtml("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + getResources().getString(R.string.home) ) );
        version.setText(Html.fromHtml(Constants.Ver_Text + Constants.VERSION));
        if (Constants.isNetworkAvailable(HomeActivity.this)) {
           setUI();
           Constants.ProgressDialogShow(HomeActivity.this);
        } else {
           Constants.getToast(HomeActivity.this,"Please check internet connection");
        }
        super.onCreate(savedInstanceState);
     }

     private void setUI(){
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(250, TimeUnit.SECONDS);
        client.setReadTimeout(250,    TimeUnit.SECONDS);
        client.setWriteTimeout(250,   TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.MenuBar)
                .get()
                .addHeader(Constants.Type,                                  Constants.App_json)
                .addHeader(getResources().getString(R.string.accesstoken),  preferenceManager.getCustToken())
                .addHeader(getResources().getString(R.string.storeidtoken), preferenceManager.getStoreId())
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, final IOException e){
                runOnUiThread(() -> {
                   Constants.getToast(HomeActivity.this,e.getMessage());
                   Constants.ProgressDialogDismiss();
                });
             }
             @Override
             public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                 try {
                     Constants.ProgressDialogDismiss();
                     arrayList = new ArrayList<>();
                     final String Response = response.body().string();
                     if(response.code() == 200) {
                         final JSONObject object = new JSONObject(Response);
                         if (object.getInt("success") == 1) {
                            JSONArray jsonArray = object.getJSONArray("data");
                            for(int i = 0; i < jsonArray.length(); i++) {
                              arrayList.add(jsonArray.get(i).toString());
                            }
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(() -> {
                              recyclerView.setLayoutManager(new GridLayoutManager(HomeActivity.this, 2));
                              MenuAdapter menuAdapter = new MenuAdapter(HomeActivity.this, arrayList);
                              recyclerView.setAdapter(menuAdapter);
                            });
                            Log.e("Size", String.valueOf(arrayList.size()));
                         } else if (object.getInt("success") == 3) {
                            runOnUiThread(() -> {
                                try{
                                    //Log.e("session", object.getString("msg"));
                                    preferenceManager.setLogged(false);
                                    Constants.getToast(HomeActivity.this, object.getString("msg"));
                                    Login.logout(HomeActivity.this);
                                } catch(JSONException e) {
                                  e.printStackTrace();
                                 }
                            });
                         }
                     } else {
                        runOnUiThread(() -> Constants.getToast(HomeActivity.this,Response));
                     }
                 } catch(NullPointerException | JSONException io) {
                    io.printStackTrace();
                 } finally {
                    response.body().close();
                 }
             }
         });
     }

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

     @Override
     public boolean onOptionsItemSelected(@NonNull MenuItem item){
         switch(item.getItemId()){
            case R.id.dashboard_logout:
               if(Constants.isNetworkAvailable(HomeActivity.this)){
                  Logout(Logout+preferenceManager.getUserId());
                  Constants.ProgressDialogShow(HomeActivity.this);
               }else{
                  Constants.getToast(HomeActivity.this,getResources().getString(R.string.connection));
               }
               break;
         }
         return super.onOptionsItemSelected(item);
     }

     public void Logout(String Url){
         final OkHttpClient client = new OkHttpClient();
         client.setConnectTimeout(240, TimeUnit.SECONDS);
         client.setReadTimeout(240,TimeUnit.SECONDS);
         client.setWriteTimeout(240,TimeUnit.SECONDS);
         final Request request     = new Request.Builder()
                 .url(Url)
                 .get()
                 .addHeader(Constants.Type,                                 Constants.App_json)
                 .addHeader(getResources().getString(R.string.accesstoken), preferenceManager.getCustToken())
                 .addHeader(getResources().getString(R.string.storeidtoken),preferenceManager.getStoreId())
                 .build();
         client.newCall(request).enqueue(new Callback(){
             @Override
             public void onFailure(Request request, IOException e){
                 Constants.ProgressDialogDismiss();
             }
             @Override
             public void onResponse(Response response) throws IOException{
                 Constants.ProgressDialogDismiss();
                     final String res = response.body().string();
                     try {
                         //Log.e("Dashboard Logout ", res);
                         if(response.code() == 200) {
                             JSONObject jsonObject = new JSONObject(res);
                             if (jsonObject.has("success")) {
                                 if (jsonObject.getInt("success") == 1) {
                                     preferenceManager.setUserId("");
                                     preferenceManager.setLogged(false);
                                     preferenceManager.setCustToken("");
                                     preferenceManager.setStoreId("");
                                     preferenceManager.setBLUETOOTH("");
                                     Login.logout(HomeActivity.this);
                                 } else {
                                     Constants.getToast(HomeActivity.this, jsonObject.getString("msg"));
                                 }
                             }
                         } else {
                             runOnUiThread(() -> Constants.getToast(HomeActivity.this, res));
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     } catch (NullPointerException np) {
                         np.printStackTrace();
                     }
                 }
         });
     }

     @Override
     public void onBackPressed(){
         int count = 0;
         if(count>0) {
            super.onBackPressed();
         }else {
            AlertDialog alert = new AlertDialog.Builder(this)
               .setTitle("Are you sure you want to close this app")
               .setPositiveButton("Yes", (dialogInterface, i) -> finish())
               .setNegativeButton("No", (dialogInterface, i) -> {
            }).show();
         }
     }
 }
