package w.soulofpluto.posstock;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
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.view.View;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
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.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.channels.InterruptedByTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static w.soulofpluto.posstock.Constants.JSON;
import static w.soulofpluto.posstock.Constants.Logout;

 /*
 Create by Ramesh Babu
 */

 public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
     Toolbar home_toolbar;
     static PreferenceManager preferenceManager;
     TextView version;
     ArrayList<String> arrayList;
     RecyclerView recyclerView;
     private static final int REQUEST_PERMISSION = 100;
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState){
         setContentView(R.layout.activity_home);
         requestRuntimePermission();

         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(getResources().getString(R.string.home));
         version.setText(Html.fromHtml(Constants.Ver_Text +Constants.VERSION));

         if(Constants.isNetworkAvailable(HomeActivity.this)) {
           setUI();
         } else {
           Constants.getToast(HomeActivity.this,"Please check internet connection");
         }
         super.onCreate(savedInstanceState);
     }
     private void requestRuntimePermission() {
         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
             return;
         }

         int permissionStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
         int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);

         List<String> requestPermissions = new ArrayList<>();

         if (permissionStorage == PackageManager.PERMISSION_DENIED) {
             requestPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
         }
         if (permissionLocation == PackageManager.PERMISSION_DENIED) {
             requestPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
         }

         if (!requestPermissions.isEmpty()) {
             ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_PERMISSION);
         }

         //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_BACKGROUND_LOCATION}, REQUEST_PERMISSION);

     }

     @Override
     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
         if (requestCode != REQUEST_PERMISSION || grantResults.length == 0) {
             return;
         }
         List<String> requestPermissions = new ArrayList<>();

         for(int i = 0; i < permissions.length; i++){
             if(permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                     && grantResults[i] == PackageManager.PERMISSION_DENIED) {
                 requestPermissions.add(permissions[i]);
             }
             if (permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
                     && grantResults[i] == PackageManager.PERMISSION_DENIED) {
                 requestPermissions.add(permissions[i]);
             }
         }

         if (!requestPermissions.isEmpty()) {
             ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_PERMISSION);
         }
     }
     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(new Runnable(){
                     @Override
                     public void run(){
                         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();
                     Log.e("MenuBar Response " ,  Response);
                     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(new Runnable() {
                                 @Override
                                 public void run() {
                                     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(new Runnable() {
                                 @Override
                                 public void run() {
                                     try {
                                         Log.e("session", object.getString("msg"));
                                         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("Content-Type", "application/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")
                     //.setMessage("Are you sure to Exit")
                     .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                         @Override
                         public void onClick(DialogInterface dialogInterface, int i){
                             finish();
                         }
                     })
                     .setNegativeButton("No", new DialogInterface.OnClickListener(){
                         @Override
                         public void onClick(DialogInterface dialogInterface, int i){
                         }
                     })
                     .show();
         }
     }

     @Override
     public void onClick(View view) {
       switch (view.getId()){
          /* case R.id.layout1:
               Intent intent = new Intent(HomeActivity.this,DashBoardActivity.class);
               startActivity(intent);
            break;*/
       }
     }
 }
