package w.soulofpluto.posstock;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
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.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
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.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.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;

 /*
  Create by Ramesh Babu
 */

public class PlanDetails extends AppCompatActivity implements View.OnClickListener {
    Toolbar plandetails_toolbar;
    EditText barcode, qty, rack_number;
    RecyclerView barcode_recylerview;
    Button ScanComplete;
    TextView plandetails_id, plandetails_name, dummy_qty, count;
    ArrayList<Plans> arrayList;
    RadioButton pieces, meters;
    RadioGroup radioGroup;
    LinearLayout pieces_layout;
    Plans plans;
    PreferenceManager preferenceManager;
    Boolean status = true;
    PlanDetailsAdapter planDetailsAdapter;
    private String Response;
    Dialog dialog;

    public static void start(Context context, Plans plans){
       Intent in = new Intent(context, PlanDetails.class);
       in.putExtra("key", plans);
       context.startActivity(in);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
       setContentView(R.layout.activity_plandetials);
       super.onCreate(savedInstanceState);
       setupdate();
    }

    private void setupdate(){
       plandetails_toolbar      = findViewById(R.id.plandetails_toolbar);
       barcode                  = findViewById(R.id.barcode);
       qty                      = findViewById(R.id.qty);
       dummy_qty                = findViewById(R.id.dummy_qty);
       rack_number              = findViewById(R.id.rack_number);
       count                    = findViewById(R.id.count);
       barcode_recylerview      = findViewById(R.id.barcode_recylerview);
       ScanComplete             = findViewById(R.id.ScanComplete);
       plandetails_id           = findViewById(R.id.plandetails_id);
       plandetails_name         = findViewById(R.id.plandetails_name);
       pieces                   = findViewById(R.id.pieces);
       meters                   = findViewById(R.id.meters);
       radioGroup               = findViewById(R.id.radio_group);
       pieces_layout            = findViewById(R.id.pieces_layout);
       arrayList                = new ArrayList<>();
       preferenceManager        = new PreferenceManager(this);
       setSupportActionBar(plandetails_toolbar);
       getSupportActionBar().setTitle(getResources().getString(R.string.plan_details));
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       plans = getIntent().getParcelableExtra(getResources().getString(R.string.key));
       barcode.requestFocus();
       plandetails_id.setText(Html.fromHtml(Constants.Plan_Id + plans.getPlanId()));
       plandetails_name.setText(Html.fromHtml(Constants.Name+ plans.getName()));
       ScanComplete.setOnClickListener(this);
       if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
         barcode.setShowSoftInputOnFocus(false);
       }
       barcode.addTextChangedListener(new AutoChecked());
       pieces.setChecked(true);
       barcode.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View view, boolean hasFocus){
                if(!hasFocus){
                }else{
                  Constants.hideSoftKeyboard(barcode,PlanDetails.this);
                }
            }
        });
    }
    public void PiecesClicked(View view){
        boolean checked = ((RadioButton) view).isChecked();
        switch(view.getId()){
            case R.id.pieces:
               if(checked){
                   status = true;
                   qty.setVisibility(View.INVISIBLE);
                   dummy_qty.setVisibility(View.INVISIBLE);
                   barcode.setText("");
               }else{
                   status = false;
                   qty.setVisibility(View.VISIBLE);
                   dummy_qty.setVisibility(View.VISIBLE);
               }
               break;
        }
    }
    public void MetersClicked(View view){
        boolean checked = ((RadioButton) view).isChecked();
        switch (view.getId()){
            case R.id.meters:
                if(checked){
                    status = false;
                    qty.setVisibility(View.VISIBLE);
                    dummy_qty.setVisibility(View.VISIBLE);
                    barcode.setText("");
                }else{
                    status = true;
                    qty.setVisibility(View.INVISIBLE);
                    dummy_qty.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    public class AutoChecked 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(PlanDetails.this)){
                    if(val.toString().contains("\n")){
                        if(status){
                            if(Constants.isNetworkAvailable(PlanDetails.this)){
                                if(arrayList.size() > 0){
                                    if(Constants.Existing(arrayList, barcode.getText().toString().replace("\n", ""))){
                                        //Constants.getToast(PlanDetails.this, "Already scanned this item");
                                        //barcode.setText("");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                MediaPlayer mp;
                                                mp = MediaPlayer.create(PlanDetails.this, R.raw.beep);
                                                mp.start();
                                                final Dialog dialog1 = new Dialog(PlanDetails.this);
                                                dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                                dialog1.setContentView(R.layout.activity_dialog);
                                                dialog1.setCancelable(false);
                                                dialog1.setCanceledOnTouchOutside(false);
                                                dialog1.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                                dialog1.show();
                                                TextView message = dialog1.findViewById(R.id.message);
                                                Button ok = dialog1.findViewById(R.id.ok);
                                                message.setText("Already scanned this item");
                                                ok.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View view) {
                                                        dialog1.dismiss();
                                                        barcode.setFocusable(true);
                                                        barcode.requestFocus();
                                                        barcode.setText("");
                                                    }
                                                });
                                            }
                                        });
                                        return;
                                    }
                                }
                                UploadBarcode(barcode.getText().toString().replace("\n", ""), "1", plans.getPlanId());
                                Constants.ProgressDialogShow(PlanDetails.this);
                                barcode.setText("");
                            }else{
                               Constants.getToast(PlanDetails.this, getResources().getString(R.string.connection));
                            }
                        }else{
                            if(TextUtils.isEmpty(qty.getText().toString())){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        barcode.setText("");
                                        Constants.getToast(PlanDetails.this, "Enter Qty");
                                    }
                                });
                            }else{
                                float value = Float.parseFloat(qty.getText().toString());
                                if(value > 0){
                                    if(Constants.isNetworkAvailable(PlanDetails.this)){
                                        //barcode.setFocusable(false);
                                        if(arrayList.size() > 0){
                                            if (Constants.Existing(arrayList, barcode.getText().toString().replace("\n", ""))) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        MediaPlayer mp;
                                                        mp = MediaPlayer.create(PlanDetails.this, R.raw.beep);
                                                        mp.start();
                                                        final Dialog dialog1 = new Dialog(PlanDetails.this);
                                                        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                                        dialog1.setContentView(R.layout.activity_dialog);
                                                        dialog1.setCancelable(false);
                                                        dialog1.setCanceledOnTouchOutside(false);
                                                        dialog1.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                                        dialog1.show();
                                                        TextView message = dialog1.findViewById(R.id.message);
                                                        Button ok = dialog1.findViewById(R.id.ok);
                                                        message.setText("Already scanned this item");
                                                        ok.setOnClickListener(new View.OnClickListener(){
                                                            @Override
                                                            public void onClick(View view){
                                                               dialog1.dismiss();
                                                               barcode.setFocusable(true);
                                                               barcode.requestFocus();
                                                               barcode.setText("");
                                                            }
                                                        });
                                                    }
                                                });
                                                return;
                                            }
                                        }
                                        UploadBarcode(barcode.getText().toString().replace("\n", ""), qty.getText().toString(), plans.getPlanId());
                                        Constants.ProgressDialogShow(PlanDetails.this);
                                        barcode.setText("");
                                    }else{
                                        Constants.getToast(PlanDetails.this, getResources().getString(R.string.connection));
                                    }
                                }
                            }
                        }
                    }
                }else{
                    Constants.getToast(PlanDetails.this, getResources().getString(R.string.connection));
                }
            }catch(NullPointerException np){
                np.printStackTrace();
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    }
    @Override
    public void onClick(View view){
        switch(view.getId()){
            case R.id.ScanComplete:
                if(Constants.isNetworkAvailable(PlanDetails.this)){
                    if(arrayList.size() > 0 ){
                        if(Constants.isNetworkAvailable(PlanDetails.this)){
                            if(rack_number.getText().toString().length()>0){
                               Constants.ProgressDialogShow(PlanDetails.this);
                               UploadAllBarcodes(Constants.BarcodeComplete,rack_number.getText().toString());
                            }else{
                               Constants.getToast(PlanDetails.this,"Enter Rack Id");
                            }
                        }else{
                           Constants.getToast(PlanDetails.this,getResources().getString(R.string.connection));
                        }
                    }else{
                       Constants.getToast(PlanDetails.this, "No Scan items ");
                    }
                }else{
                    Constants.getToast(PlanDetails.this, getResources().getString(R.string.connection));
                }
                break;
        }
    }
    public void UploadAllBarcodes(String barcodeall,String rack){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
               object.put(getResources().getString(R.string.rack_no),rack);
               object.put(getResources().getString(R.string.android_version),Constants.VERSION);
            }
        }catch(JSONException e){
          e.printStackTrace();
        }
        Log.e("Upload All", 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(barcodeall)
                .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(){
                       Toast.makeText(PlanDetails.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                       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("upload all  Response ", 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.getInt(getResources().getString(R.string.success)) == 1) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Constants.getToast(PlanDetails.this, "Uploaded Successfully");
                                            }
                                        });
                                        finish();
                                    }else if(object.getInt(getResources().getString(R.string.success)) == 3){
                                        runOnUiThread(new Runnable(){
                                            @Override
                                            public void run(){
                                                try{
                                                   Constants.getToast(PlanDetails.this, object.getString(getResources().getString(R.string.msg)));
                                                   DoLogin();
                                                }catch(JSONException e){
                                                   e.printStackTrace();
                                                }
                                            }
                                        });
                                    }else{
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try{
                                                    Constants.getToast(PlanDetails.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 void UploadBarcode(final String Barcode, final String qty, final String Id){
        JSONObject object = new JSONObject();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                object.put(getResources().getString(R.string.barcode_upload), Barcode);
                object.put(getResources().getString(R.string.rule_id), Id);
                object.put(getResources().getString(R.string.quantity_upload), qty);
                object.put(getResources().getString(R.string.android_version), Constants.VERSION);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("Upload Barcode", 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(Constants.BarcodeUpload)
                .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(PlanDetails.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("Upload Barcode", 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){
                                            barcode.requestFocus();
                                            Plans plans = new Plans();
                                            plans.setQty(qty);
                                            plans.setPlanId(Id);
                                            plans.setBarcode(Barcode);
                                            arrayList.add(plans);
                                            Collections.reverse(arrayList);
                                            if(arrayList.size() > 0){
                                                planDetailsAdapter = new PlanDetailsAdapter(PlanDetails.this, arrayList);
                                                barcode_recylerview.setLayoutManager(new LinearLayoutManager(PlanDetails.this));
                                                barcode_recylerview.setAdapter(planDetailsAdapter);
                                            }
                                            setUI(arrayList);
                                        }else if(object.getInt(getResources().getString(R.string.success)) == 3){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try{
                                                       Constants.getToast(PlanDetails.this, object.getString(getResources().getString(R.string.msg)));
                                                       DoLogin();
                                                    }catch(JSONException e){
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                        }else{
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MediaPlayer mp;
                                                    mp = MediaPlayer.create(PlanDetails.this, R.raw.beep);
                                                    mp.start();
                                                    final Dialog dialog1 = new Dialog(PlanDetails.this);
                                                    dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                                    dialog1.setContentView(R.layout.activity_dialog);
                                                    dialog1.setCancelable(false);
                                                    dialog1.setCanceledOnTouchOutside(false);
                                                    dialog1.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                                    dialog1.show();
                                                    TextView message = dialog1.findViewById(R.id.message);
                                                    Button ok = dialog1.findViewById(R.id.ok);
                                                    try{
                                                       message.setText(object.getString(getResources().getString(R.string.msg)));
                                                    }catch(JSONException e){
                                                       e.printStackTrace();
                                                    }
                                                    ok.setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View view) {
                                                            dialog1.dismiss();
                                                            barcode.setFocusable(true);
                                                            barcode.requestFocus();
                                                            barcode.setText("");
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    public void DeleteBarcode(final Plans plans, final int position){
        Constants.ProgressDialogShow(PlanDetails.this);
        final JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
               object.put(getResources().getString(R.string.barcode_upload), plans.getBarcode());
               object.put(getResources().getString(R.string.rule_id), plans.getPlanId());
               object.put(getResources().getString(R.string.quantity_upload), plans.getQty());
               object.put(getResources().getString(R.string.android_version),Constants.VERSION);
            }
        }catch(JSONException e){
          e.printStackTrace();
        }
        Log.e("delele Barcode ", 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(Constants.BarcodeDelete)
                .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.ProgressDialogDismiss();
                        Constants.getToast(PlanDetails.this, e.getMessage());
                    }
                });
            }
            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Constants.ProgressDialogDismiss();
                    String res = response.body().string();
                    Log.e("delete Barcode Response", res);
                    try {
                        final JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.has(getResources().getString(R.string.success))) {
                            if(jsonObject.getInt(getResources().getString(R.string.success)) == 1){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Constants.getToast(PlanDetails.this, jsonObject.getString(getResources().getString(R.string.data)));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        arrayList.remove(position);
                                        planDetailsAdapter.notifyDataSetChanged();
                                        setUI(arrayList);
                                    }
                                });

                            }else if (jsonObject.getInt(getResources().getString(R.string.success)) == 3){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try{
                                            Constants.getToast(PlanDetails.this, jsonObject.getString(getResources().getString(R.string.msg)));
                                            DoLogin();
                                        }catch(JSONException e){
                                           e.printStackTrace();
                                        }
                                    }
                                });
                            } else{
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try{
                                            Constants.getToast(PlanDetails.this, jsonObject.getString(getResources().getString(R.string.msg)));
                                        }catch(JSONException e){
                                          e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (NullPointerException np){
                        np.printStackTrace();
                    }
                }
            }
        });
    }

    public void setUI(final ArrayList<Plans> list){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(list.size() > 0) {
                   count.setText("Scanned Items : " + list.size());
                }else {
                   count.setText("Scanned Items : 0 ");
                }
            }
        });
    }

    private void DoLogin(){
        dialog = new Dialog(PlanDetails.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_session);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.show();
        final TextView userId    = dialog.findViewById(R.id.relogin_userid);
        final TextView pass      = dialog.findViewById(R.id.relogin_pass);
        final Button   reLogin   = dialog.findViewById(R.id.relogin_submit);
        userId.setText(preferenceManager.getUserId());
        //pass.setText(preferenceManager.getPassword());
        reLogin.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(Constants.isNetworkAvailable(PlanDetails.this)){
                   if(TextUtils.isEmpty(pass.getText().toString())){
                     Constants.getToast(PlanDetails.this,getResources().getString(R.string.enterPassword));
                   }else{
                     doLogin(preferenceManager.getUserId(), Constants.getSHA256(pass.getText().toString()));
                     Constants.ProgressDialogShow(PlanDetails.this);
                   }
                }else{
                    Constants.getToast(PlanDetails.this,getResources().getString(R.string.connection));
                }
            }
        });
    }

    private void doLogin(String userId, String pass){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                object.put(getResources().getString(R.string.empid),   userId);
                object.put(getResources().getString(R.string.password),pass);
                object.put(getResources().getString(R.string.storeid), preferenceManager.getStoreId());
                object.put(getResources().getString(R.string.dongle),false);
                object.put(getResources().getString(R.string.android_version),Constants.VERSION);
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(100, TimeUnit.SECONDS);
        client.setReadTimeout(100, TimeUnit.SECONDS);
        client.setWriteTimeout(100, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.Login)
                .post(body)
                .addHeader(Constants.Type, Constants.App_json)
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, IOException e){
                if(e.getCause() != null && e.getCause() instanceof UnknownHostException){
                }else{
                  Log.e("error ====>" , e.getMessage());
                }
                Constants.ProgressDialogDismiss();
            }
            @Override
            public void onResponse(final Response response) throws IOException{
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try{
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            if(response.code() == 200){
                                try{
                                    JSONObject obj = new JSONObject(Response);
                                    if(obj.has(getResources().getString(R.string.success))){
                                        if(obj.getInt(getResources().getString(R.string.success)) == 1 ){
                                            JSONObject data = obj.getJSONObject(getResources().getString(R.string.data));
                                            preferenceManager.setUserId(data.getString(getResources().getString(R.string.empid)));
                                            preferenceManager.setCustToken(data.getString(getResources().getString(R.string.usertoken)));
                                            preferenceManager.setStoreId(data.getString(getResources().getString(R.string.storeid)));
                                            preferenceManager.setPrefix(data.getString(getResources().getString(R.string.prefix)));
                                            preferenceManager.setLogged(true);
                                            dialog.dismiss();
                                        }else{
                                            Toast.makeText(PlanDetails.this,obj.getString(getResources().getString(R.string.msg)), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }catch(JSONException e){
                                  e.printStackTrace();
                                }catch (NullPointerException np){
                                  np.printStackTrace();
                                }
                            }else{
                            }
                        }
                    });
                }catch(NullPointerException io){
                    io.printStackTrace();
                }finally{
                    response.body().close();
                }
            }
        });
    }

    @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", 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();
        }
    }
}
