package w.soulofpluto.posstock;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
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 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 SearchByBarcode extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    Toolbar  searchbybarcode_toolbar;
    Spinner  searchbybarcode_spinner;
    EditText searchby_barcode;
    TextView searchbybarcode_rack;
    ArrayList<Plans> arrayList;
    PreferenceManager preferenceManager;
    String planid;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_searchbybarcode);
      searchbybarcode_toolbar = findViewById(R.id.searchbybarcode_toolbar);
      searchbybarcode_spinner = findViewById(R.id.searchbybarcode_spinner);
      searchbybarcode_rack    = findViewById(R.id.searchbybarcode_rack);
      searchby_barcode        = findViewById(R.id.searchbybarcode_edit);
      preferenceManager       = new PreferenceManager(this);
      setSupportActionBar(searchbybarcode_toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      getSupportActionBar().setTitle("Barcode Search");
      if(Constants.isNetworkAvailable(this)){
        FetchData(Constants.Dashboard);
        Constants.ProgressDialogShow(SearchByBarcode.this);
      }else{
        Constants.getToast(SearchByBarcode.this,getResources().getString(R.string.connection));
      }
      searchbybarcode_spinner.setOnItemSelectedListener(this);
     /*
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        searchby_barcode.setShowSoftInputOnFocus(false);
      }*/
      searchby_barcode.addTextChangedListener(new Checked());
    }

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

    public void getBarcodeCheck(String planId, final String Barcode){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
              object.put(getResources().getString(R.string.plan_id),planId);
              object.put(getResources().getString(R.string.barcode_upload), Barcode);
              object.put(getResources().getString(R.string.android_version),Constants.VERSION);
            }
        }catch(JSONException e){
           e.printStackTrace();
        }
        Log.e("Search", object.toString());
        RequestBody body = RequestBody.create(JSON, object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(25, TimeUnit.SECONDS);
        client.setReadTimeout(25, TimeUnit.SECONDS);
        client.setWriteTimeout(25, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.BarcodeSearch)
                .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(SearchByBarcode.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("Barcode Search", Response);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            try{
                                final JSONObject object = new JSONObject(Response);
                                if(response.code() == 200) {
                                    if (object.has(getResources().getString(R.string.success))) {
                                        if(object.getInt(getResources().getString(R.string.success)) == 1) {
                                            Log.e("Length",String.valueOf(getResources().getString(R.string.data).length()));
                                            if(object.has(getResources().getString(R.string.data))){
                                                if(object.getString(getResources().getString(R.string.msg)).equalsIgnoreCase("no data found")){
                                                    searchby_barcode.setText("");
                                                    searchbybarcode_rack.setText(object.getString(getResources().getString(R.string.msg)));
                                                    //Constants.getToast(SearchByBarcode.this, object.getString(getResources().getString(R.string.msg)));
                                                }else{
                                                    searchby_barcode.setText("");
                                                    try{
                                                        JSONObject jsonObject = object.getJSONObject(getResources().getString(R.string.data));
                                                        searchbybarcode_rack.setText(Html.fromHtml(Constants.Id) + jsonObject.getString("rack_id") + "\n"
                                                                                 + (Html.fromHtml(Constants.Barcode) + jsonObject.getString("barcode")) + "\n"
                                                                                 + (Html.fromHtml(Constants.From) + jsonObject.getString("scanning_start_at")) + "\n"
                                                                                 + (Html.fromHtml(Constants.To) + jsonObject.getString("scanning_end_at")));
                                                    }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(SearchByBarcode.this, object.getString(getResources().getString(R.string.msg)));
                                                    }catch(JSONException e){
                                                      e.printStackTrace();
                                                    }
                                                }
                                            });
                                        }else{
                                            try{
                                                Constants.getToast(SearchByBarcode.this, object.getString(getResources().getString(R.string.msg)));
                                            }catch(JSONException e){
                                              e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }catch(NullPointerException io){
                   io.printStackTrace();
                }finally{
                   response.body().close();
                }
            }
        });
    }

    public class Checked implements TextWatcher{
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2){
        }
        @Override
        public void onTextChanged(CharSequence val, int i, int i1, int i2){
            try{
                if(Constants.isNetworkAvailable(SearchByBarcode.this)) {
                    if(val.toString().length() > 0) {
                        if(planid.equalsIgnoreCase("0")) {
                            Constants.getToast(SearchByBarcode.this, "Choose Plan Id");
                            searchby_barcode.setText("");
                        }
                        if (val.toString().contains("\n")) {
                            if (Constants.isNetworkAvailable(SearchByBarcode.this)) {
                                if (planid.equalsIgnoreCase("0")) {
                                    Constants.getToast(SearchByBarcode.this, "Choose Plan Id");
                                    searchby_barcode.setText("");
                                } else {
                                    getBarcodeCheck(planid, searchby_barcode.getText().toString().replace("\n", ""));
                                    Constants.ProgressDialogShow(SearchByBarcode.this);
                                }
                            } else {
                                Constants.getToast(SearchByBarcode.this, getResources().getString(R.string.connection));
                            }
                        }
                    }
                }
            }catch(NullPointerException np){
               np.printStackTrace();
            }
        }
        @Override
        public void afterTextChanged(Editable editable){
        }
    }

    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("Searchby object ====>",object.toString());
        RequestBody body = RequestBody.create(JSON,object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(25, TimeUnit.SECONDS);
        client.setReadTimeout(25, TimeUnit.SECONDS);
        client.setWriteTimeout(25, 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(SearchByBarcode.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("SearchByBarcode" ,  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>(SearchByBarcode.this, android.R.layout.simple_dropdown_item_1line, arrayList);
                                                searchbybarcode_spinner.setAdapter(adapter);
                                            }else if (object.has(getResources().getString(R.string.msg))){
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        try{
                                                            Constants.getToast(SearchByBarcode.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(SearchByBarcode.this, object.getString(getResources().getString(R.string.msg)));
                                                    }catch(JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                            preferenceManager.setUserId("");
                                            preferenceManager.setLogged(false);
                                            preferenceManager.setCustToken("");
                                            preferenceManager.setStoreId("");
                                            Login.logout(SearchByBarcode.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.searchbybarcode_spinner:
              Plans plan = arrayList.get(i);
              planid = plan.PlanId;
              Log.e("Search by barcode ===>",planid);
              if(planid.equalsIgnoreCase("0")){
                //Constants.getToast(RackWiseQty.this,"Please Choose PlanId");
                searchbybarcode_rack.setText("");
              }else{
                searchbybarcode_rack.setText("");
              }
           break;
      }
    }
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
    }
}
