package w.soulofpluto.posstock;

import android.content.res.Configuration;
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.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;
import static w.soulofpluto.posstock.Constants.getDateWithOffset;

 /*
  Create by Ramesh Babu
 */

public class RackWiseQty extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    PreferenceManager preferenceManager;
    ArrayList<Plans> arrayList;
    TextView total_scanned;
    ArrayList<RackWise> rackWiseArrayList;
    RecyclerView rack_recylerview;
    Spinner rack_spinner;
    Toolbar rackwise_toolbar;
    String rackid;
    RackWiseAdapter rackWiseAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        setContentView(R.layout.activity_ractwiseqty);
        preferenceManager = new PreferenceManager(this);
        rack_recylerview  = findViewById(R.id.rack_recylerview);
        rack_spinner      = findViewById(R.id.rack_spinner);
        rackwise_toolbar  = findViewById(R.id.rackwise_toolbar);
        total_scanned     = findViewById(R.id.total_scanned);
        rackWiseArrayList = new ArrayList<>();
        setSupportActionBar(rackwise_toolbar);
        getSupportActionBar().setTitle("RackWise Qty");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if(Constants.isNetworkAvailable(this)){
          FetchData(Constants.Dashboard);
          Constants.ProgressDialogShow(RackWiseQty.this);
        }else{
          Constants.getToast(RackWiseQty.this,getResources().getString(R.string.connection));
        }
        rack_spinner.setOnItemSelectedListener(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
               finish();
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void FetchData(String Url){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
                Date todayDate = new Date();
                Date from = getDateWithOffset(-Constants.Value, new Date());
                String fromDate = currentDate.format(from);
                String thisDate = currentDate.format(todayDate);
                Log.e("Last date",fromDate);
                object.put(getResources().getString(R.string.auditstatus),"In Progress");
                object.put(getResources().getString(R.string.fromdate),fromDate);
                object.put(getResources().getString(R.string.todate),thisDate);
            }
        }catch(JSONException e){
          e.printStackTrace();
        }
        Log.e("Rackwise object ====>",object.toString());
        RequestBody body = RequestBody.create(JSON,object.toString());
        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(Url)
                .post(body)
                .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(RackWiseQty.this,e.getMessage());
                        Constants.ProgressDialogDismiss();
                    }
                });
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException{
                try{
                    Constants.ProgressDialogDismiss();
                    final String Response = response.body().string();
                    Log.e("Store Response " ,  Response);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            try{
                                if(response.code() == 200){
                                    final JSONObject object = new JSONObject(Response);
                                    if(object.has(getResources().getString(R.string.success))){
                                        arrayList = new ArrayList<>();
                                        if(object.getInt(getResources().getString(R.string.success)) == 1){
                                            if(object.has(getResources().getString(R.string.data))){
                                                arrayList.clear();
                                                Plans plan = new Plans();
                                                plan.setPlanId("0");
                                                plan.setName("Select PlanId");
                                                arrayList.add(plan);
                                                JSONArray jsonArray = object.getJSONArray(getResources().getString(R.string.data));
                                                for (int i = 0; i < jsonArray.length(); i++) {
                                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                                    Plans plans = new Plans();
                                                    plans.setPlanId(String.valueOf(jsonObject.getInt("id")));
                                                    plans.setName(jsonObject.getString("stock_audit_name"));
                                                    arrayList.add(plans);
                                                }
                                                ArrayAdapter<Plans> adapter = new ArrayAdapter<Plans>(RackWiseQty.this, android.R.layout.simple_dropdown_item_1line, arrayList);
                                                rack_spinner.setAdapter(adapter);
                                            }else if (object.has(getResources().getString(R.string.msg))){
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        try{
                                                           Constants.getToast(RackWiseQty.this, object.getString(getResources().getString(R.string.msg)));
                                                        }catch(JSONException e){
                                                          e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            }
                                        }else if(object.getInt(getResources().getString(R.string.success)) == 3){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try{
                                                        Constants.getToast(RackWiseQty.this, object.getString(getResources().getString(R.string.msg)));
                                                    }catch(JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                            preferenceManager.setUserId("");
                                            preferenceManager.setLogged(false);
                                            preferenceManager.setCustToken("");
                                            preferenceManager.setStoreId("");
                                            Login.logout(RackWiseQty.this);
                                        }
                                    }
                                }
                            }catch(JSONException e){
                                e.printStackTrace();
                            }
                        }
                    });
                }catch(NullPointerException io){
                    io.printStackTrace();
                }finally{
                    response.body().close();
                }
            }
        });
    }
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l){
        switch (adapterView.getId()){
            case R.id.rack_spinner:
                Plans plan = arrayList.get(i);
                rackid = plan.PlanId;
                if(rackid.equalsIgnoreCase("0")){
                    runOnUiThread(new Runnable(){
                        @Override
                        public void run(){
                            total_scanned.setText(Html.fromHtml(Constants.getVal(0)));
                            rack_recylerview.setAdapter(null);
                        }
                    });
                }else{
                   if(Constants.isNetworkAvailable(this)){
                     try {
                         getRackWiseData(rackid);
                         Constants.ProgressDialogShow(RackWiseQty.this);
                     }catch (NullPointerException np){
                         np.printStackTrace();
                     }catch (NumberFormatException npe){
                         npe.printStackTrace();
                     }
                   }else{
                     Constants.getToast(RackWiseQty.this,getResources().getString(R.string.connection));
                   }
                }
                break;
        }
    }
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
    }
    private void getRackWiseData(String planid){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
              object.put(getResources().getString(R.string.plan_id),planid);
            }
        }catch(JSONException e){
           e.printStackTrace();
        }catch (NullPointerException np){
           np.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,object.toString());
        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.RackWiseQty)
                .post(body)
                .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(RackWiseQty.this,e.getMessage());
                        Constants.ProgressDialogDismiss();
                    }
                });
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException{
                try{
                    Constants.ProgressDialogDismiss();
                    final String Response = response.body().string();
                    Log.e("Rackwise Response " ,  Response);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            try{
                                if(response.code() == 200){
                                    final JSONObject object = new JSONObject(Response);
                                    if(object.has(getResources().getString(R.string.success))){
                                        if(object.getInt(getResources().getString(R.string.success)) == 1){
                                            if(object.has(getResources().getString(R.string.data))){
                                                rackWiseArrayList.clear();
                                                JSONObject headerobject = object.getJSONObject(getResources().getString(R.string.data));
                                                final int count = headerobject.getInt("total_scanned_items");
                                                Log.e("TOTAL SCANNED ITEMS : ",String.valueOf(count));
                                                runOnUiThread(new Runnable(){
                                                    @Override
                                                    public void run(){
                                                      total_scanned.setText(Html.fromHtml(Constants.getVal(count)));
                                                    }
                                                });
                                                JSONArray jsonArray = headerobject.getJSONArray("rack_info");
                                                //JSONArray jsonArray = object.getJSONArray(getResources().getString(R.string.data));
                                                for(int i = 0; i < jsonArray.length(); i++){
                                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                                    RackWise rackWise = new RackWise();
                                                    rackWise.setId(jsonObject.getString("rack_id"));
                                                    rackWise.setScanned_by(String.valueOf(jsonObject.getInt("scanned_by")));
                                                    rackWise.setScanning_start_at(jsonObject.getString("scanning_start_at"));
                                                    rackWise.setScanning_end_at(jsonObject.getString("scanning_end_at"));
                                                    rackWise.setQty(Integer.parseInt(jsonObject.getString("scanned_items_count")));
                                                    rackWiseArrayList.add(rackWise);
                                                }
                                                rackWiseAdapter = new RackWiseAdapter(RackWiseQty.this, rackWiseArrayList);
                                                rack_recylerview.setLayoutManager(new LinearLayoutManager(RackWiseQty.this,LinearLayoutManager.VERTICAL,false));
                                                rack_recylerview.setAdapter(rackWiseAdapter);
                                            }else if (object.has(getResources().getString(R.string.msg))){
                                                runOnUiThread(new Runnable(){
                                                    @Override
                                                    public void run(){
                                                        try{
                                                           Constants.getToast(RackWiseQty.this, object.getString(getResources().getString(R.string.msg)));
                                                        }catch(JSONException e){
                                                           e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            }
                                        }else if(object.getInt(getResources().getString(R.string.success)) == 3){
                                                runOnUiThread(new Runnable(){
                                                    @Override
                                                    public void run(){
                                                        try{
                                                            Constants.getToast(RackWiseQty.this, object.getString(getResources().getString(R.string.msg)));
                                                        }catch(JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                                preferenceManager.setUserId("");
                                                preferenceManager.setLogged(false);
                                                preferenceManager.setCustToken("");
                                                preferenceManager.setStoreId("");
                                                Login.logout(RackWiseQty.this);
                                        }
                                    }
                                }
                            }catch(JSONException e){
                              e.printStackTrace();
                            }
                        }
                    });
                }catch(NullPointerException io){
                    io.printStackTrace();
                }finally{
                    response.body().close();
                }
            }
        });
    }

}
