package w.soulofpluto.posstock;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;
import static w.soulofpluto.posstock.Constants.JsonFormatData;

 /*
 Create by Ramesh Babu
 */

public class StockReceived extends AppCompatActivity implements View.OnClickListener {
    EditText             tfSid;
    Toolbar              StockReceived_toolbar;
    PreferenceManager    preferenceManager;
    String               Response;
    ArrayList<BoxInfo>   boxInfoArrayList;
    RecyclerView         StockReceived_recyclerView;
    TextView             transfer_qty, pending_qty, received_qty;
    String               value;
    StockReceivedAdapter adapter;
    Button               stock_received;
    static int           val1, val2, val3;
    String               Tfs_Id, Box_Id;
    TextView             tfs_Number;

    static void startData(Context context, String data) {
        Intent intent = new Intent(context, StockReceived.class);
        intent.putExtra("key", data);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_received);
        tfSid                      = findViewById(R.id.tfsid);
        tfs_Number                 = findViewById(R.id.tfs_Number);
        StockReceived_recyclerView = findViewById(R.id.stockReceived_recylerView);
        StockReceived_toolbar      = findViewById(R.id.stockReceived_toolbar);
        transfer_qty               = findViewById(R.id.transfer_qty);
        pending_qty                = findViewById(R.id.pending_qty);
        received_qty               = findViewById(R.id.received_qty);
        stock_received             = findViewById(R.id.stock_received);
        preferenceManager          = new PreferenceManager(StockReceived.this);
        boxInfoArrayList           = new ArrayList<>();
        tfSid.addTextChangedListener(new Checked());
        stock_received.setOnClickListener(this);
        try{
            if(getIntent().getStringExtra("key") != null) {
                value = getIntent().getStringExtra("key");
                setSupportActionBar(StockReceived_toolbar);
                getSupportActionBar().setTitle(getResources().getString(R.string.stock_received) + " | " + value);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                if (Constants.isNetworkAvailable(this)) {
                  getCall();
                }else{
                  runOnUiThread(() -> Constants.getToast(StockReceived.this,getResources().getString(R.string.connection)));
                }
            }
        }catch (NullPointerException np) {
           np.printStackTrace();
        }
    }

    void getCall() {
        if (Constants.isNetworkAvailable(StockReceived.this)) {
            PostRequest(value);
            Log.e("Perform1 ========>", value);
        } else {
            Constants.getToast(StockReceived.this, getResources().getString(R.string.nonetwork));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

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

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.stock_received:
                 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    String str[] = received_qty.getText().toString().split(":");
                    if (!str[1].trim().equalsIgnoreCase("0") && boxInfoArrayList.stream().map(BoxInfo::getStatus).anyMatch(Boolean.TRUE::equals)) {
                        try {
                            if(Constants.isNetworkAvailable(this)) {
                                Constants.ProgressDialogShow(StockReceived.this);
                                FinalRequest(JsonFormatData(Tfs_Id, Box_Id, boxInfoArrayList, preferenceManager.getStoreId()));
                            }else{
                                runOnUiThread(() -> Constants.getToast(StockReceived.this,getResources().getString(R.string.connection)));
                            }
                        } catch(JSONException e) {
                          e.printStackTrace();
                        }
                    } else {
                       Constants.getToast(StockReceived.this, "Please Scan AtLeast one Barcode");
                    }
                 }
                break;
        }
    }

    public void FinalRequest(String res) {
        com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(JSON, res);
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.StockReceiving)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if(e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                }else{
                    runOnUiThread(() -> Constants.getToast(StockReceived.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                Log.e("Stock Transfer =====>", Response);
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            tfSid.setText("");
                            tfSid.requestFocus();
                            try {
                                JSONObject obj = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        if (obj.getString("msg").equalsIgnoreCase("TFS Received Successfully")) {
                                            finish();
                                            Constants.getToast(StockReceived.this, obj.getString("msg"));
                                            return;
                                        } else {
                                            Constants.getToast(StockReceived.this, obj.getString("msg"));
                                            getCall();
                                        }
                                    } else if (obj.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try {
                                                Login.logout(StockReceived.this);
                                                Constants.getToast(StockReceived.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockReceived.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockReceived.this, Response));
                        }
                    });
                } 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) {
        }
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onTextChanged(CharSequence val, int i, int i1, int i2) {
            try {
                    if (val.toString().length() > 0) {
                        Log.e("Barcode",val.toString());
                        if (val.toString().contains("\n")) {
                            Log.e("Barcode1",val.toString());
                            if (Constants.isNetworkAvailable(StockReceived.this)) {
                                if (boxInfoArrayList.size() > 0) {
                                    Log.e("Barcode arraysize==>",val.toString());
                                    //String value1[] = val.toString().split("\n");
                                    String value = val.toString().replace("\n","");
                                    Log.e("Value size   ======>", String.valueOf(value.length()));
                                    boolean itemExistsBasedOnProp =   boxInfoArrayList.stream().map(BoxInfo::getBarcode).anyMatch(value.replace(" ","")::equals);
                                    //boolean itemExistsBasedOnProp = boxInfoArrayList.stream().map(BoxInfo::getBarcode).anyMatch(val.toString().replace("\n", "")::equals);
                                    Log.e("Barcode value =====>", String.valueOf(itemExistsBasedOnProp));
                                    if (itemExistsBasedOnProp) {
                                        for (int k = 0; k < boxInfoArrayList.size(); k++) {
                                            BoxInfo boxInfo = boxInfoArrayList.get(k);
                                            if (boxInfo.getStatus()) {
                                                if (boxInfo.getBarcode().equalsIgnoreCase(val.toString().replace("\n", ""))) {
                                                    Constants.getToast(StockReceived.this, "Already Scanned on Same Barcode");
                                                    tfSid.setText("");
                                                    tfSid.requestFocus();
                                                    break;
                                                }
                                            }
                                            if (boxInfo.getBarcode().equalsIgnoreCase(val.toString().replace("\n", ""))) {
                                                if (boxInfo.getTransfer_qty().equalsIgnoreCase(boxInfo.getReceive_qty())) {
                                                    Constants.getToast(StockReceived.this, "Already Matched Sent and Received");
                                                    tfSid.setText("");
                                                    tfSid.requestFocus();
                                                } else {
                                                    Log.e("Insert ," , "else" );
                                                    BoxInfo boxInfo1 = new BoxInfo(boxInfo.getBarcode(), boxInfo.getUom(), boxInfo.getTransfer_qty(), "1", "0", true);
                                                    boxInfoArrayList.set(k, boxInfo1);
                                                    adapter.notifyDataSetChanged();
                                                    val2 = val2 - 1;
                                                    val3 = val3 + 1;
                                                    runOnUiThread(() -> {
                                                        transfer_qty.setText("Sent : " + val1);
                                                        pending_qty.setText( "Pending : " + val2);
                                                        received_qty.setText("Received : " + val3);
                                                        tfSid.setText("");
                                                        tfSid.requestFocus();
                                                    });
                                                }
                                                break;
                                            }
                                        }
                                    } else {
                                        runOnUiThread(() -> {
                                            Constants.getToast(StockReceived.this, "Barcode Not Found");
                                            tfSid.setText("");
                                            tfSid.requestFocus();
                                        });
                                    }
                                } else {
                                    runOnUiThread(() -> {
                                       Constants.getToast(StockReceived.this, "No Data Found");
                                       tfSid.setText("");
                                       tfSid.requestFocus();
                                    });
                                }
                            }
                        }
                    } else {
                        //Constants.getToast(StockReceived.this, "Enter TFS No");
                        //tfSid.setText("");
                        tfSid.requestFocus();
                    }
            } catch (NullPointerException jo) {
                jo.getMessage();
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    }

    public void getTFSBoxDetails(String val) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.GetTFSBoxNumbers + val)
                .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) {
            }
            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                try {
                    String res = response.body().string();
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject jsonObject = new JSONObject(res);
                                if (jsonObject.getInt(getResources().getString(R.string.success)) == 1) {
                                    String data = jsonObject.getString("data");
                                    JSONArray jsonArray = new JSONArray(data);
                                    if (jsonArray.length() > 1) {
                                        Constants.getToast(StockReceived.this, getResources().getString(R.string.AppCanNot));
                                    } else {
                                        JSONObject object = jsonArray.getJSONObject(0);
                                        Box_Id            = object.getString("id");
                                        GetTFSBoxDetailsByBarcode(val, Box_Id);
                                    }
                                } else if (jsonObject.getInt(getResources().getString(R.string.success)) == 3) {
                                    runOnUiThread(() -> {
                                        try {
                                            Constants.getToast(StockReceived.this, jsonObject.getString("msg"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        Login.logout(StockReceived.this);
                                    });
                                } else {
                                    runOnUiThread(() -> {
                                        try {
                                            Constants.getToast(StockReceived.this, jsonObject.getString("msg"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (NullPointerException npe) {
                                npe.printStackTrace();
                            }
                        }
                    });
                } catch (NullPointerException np) {
                    np.printStackTrace();
                }
            }
        });
    }

    private void GetTFSBoxDetailsByBarcode(String val, String id) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240,    TimeUnit.SECONDS);
        client.setWriteTimeout(240,   TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url( Constants.GetTFSBoxDetailsByBarcode + val + "/" + id )
                .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) {
            }
            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                String res = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            final JSONObject object;
                            try {
                                object = new JSONObject(res);
                                if (object.getInt("success") == 1) {
                                    if (object.has("data")) {
                                        JSONObject dataObject = object.getJSONObject("data");
                                        JSONArray jsonArray = dataObject.getJSONArray("box_info");
                                        boxInfoArrayList.clear();
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            BoxInfo boxInfo = new BoxInfo(jsonObject.getString("barcode"), jsonObject.getString("uom"),
                                            jsonObject.getString("transfered_qty"), jsonObject.getString("received_qty"),
                                            jsonObject.getString("pending_qty"), false);
                                            boxInfoArrayList.add(boxInfo);
                                        }
                                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(StockReceived.this, LinearLayoutManager.VERTICAL, false);
                                        adapter = new StockReceivedAdapter(StockReceived.this, boxInfoArrayList);
                                        StockReceived_recyclerView.setLayoutManager(linearLayoutManager);
                                        StockReceived_recyclerView.setAdapter(adapter);
                                        JSONObject totalJsonObject = dataObject.getJSONObject("totals");
                                        val1 = totalJsonObject.getInt("transfered_qty");
                                        val2 = totalJsonObject.getInt("pending_qty");
                                        val3 = totalJsonObject.getInt("received_qty");
                                        transfer_qty.setText("Sent :    " + totalJsonObject.getString("transfered_qty"));
                                        pending_qty.setText("Pending : "  + totalJsonObject.getString("pending_qty"));
                                        received_qty.setText("Received :" + totalJsonObject.getString("received_qty"));
                                    }
                                } else if (object.getInt("success") == 3) {
                                    runOnUiThread(() -> {
                                        try {
                                            Constants.getToast(StockReceived.this, object.getString("msg"));
                                            Login.logout(StockReceived.this);
                                        } catch (JSONException je) {
                                            je.printStackTrace();
                                        }
                                    });
                                } else {
                                    runOnUiThread(() -> {
                                        try {
                                            Constants.getToast(StockReceived.this, object.getString("msg"));
                                        } catch (JSONException je) {
                                            je.printStackTrace();
                                        }
                                    });
                                }
                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                        }
                    });
                } catch (NullPointerException np) {
                    np.printStackTrace();
                }
            }
        });
    }

    public void PostRequest(String res) {
        JSONObject jsonObject = new JSONObject();
        try{
           jsonObject.put("tfs_number", res);
        }catch(JSONException je) {
           je.printStackTrace();
        }
        com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(JSON, jsonObject.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240,    TimeUnit.SECONDS);
        client.setWriteTimeout(240,   TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.GetInfoWithTFS)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if (e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                } else {
                    runOnUiThread(() -> Constants.getToast(StockReceived.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            tfSid.setText("");
                            tfSid.requestFocus();
                            try {
                                JSONObject obj = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        String tfSid           = obj.getString("data");
                                        JSONObject jsonObject1 = new JSONObject(tfSid);
                                        Tfs_Id                 = jsonObject1.getString("tfs_id");
                                        getTFSBoxDetails(Tfs_Id);
                                    } else if (obj.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockReceived.this, obj.getString("msg"));
                                                Login.logout(StockReceived.this);
                                            } catch (JSONException je) {
                                                je.printStackTrace();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockReceived.this, obj.getString("msg"));
                                                finish();
                                            } catch (JSONException je) {
                                                je.printStackTrace();
                                            }
                                        });
                                    }
                                }
                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockReceived.this, Response));
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }
}
