package com.maxmoney.maxcddconsole.ActivityV2;

import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.maxmoney.maxcddconsole.Activity.DashboardActivity;
import com.maxmoney.maxcddconsole.Activity.LoginActivity;
import com.maxmoney.maxcddconsole.Activity.TopapActivity;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;
import com.squareup.picasso.Picasso;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.android.volley.Request.Method.GET;
import static com.android.volley.Request.Method.POST;

public class TopapActivityV2 extends AppCompatActivity implements View.OnClickListener {

//    String image_operator_url = "https://fm.transfer-to.com:5443/logo_operator/logo-"++"-2.png";

    SearchableSpinner spinner_country;
    EditText editText_receiver;
    Button button_continue;
    String session;
    StandardProgressDialog standardProgressDialog;
    TextView textView_receiver,textView_changeOperator;
    ArrayAdapter<String> spinnerNationalityAdapter;
    ImageView imageView_operator;
    Spinner spinner_value;
    LinearLayout linear_operator;
    String operator="",operatorId="",countryId="",retails_value = "",value="",whosale_price ="";
    ArrayList<String> valueNames;
    String destinationCurrency="";
    AlertDialog.Builder mBuilderOperator;
    AlertDialog mDialogOperator;
    ArrayList<String> operatorNames;
    LinearLayout linear_details;
    TextView textView_amount,textView_topapRate,textView_serviceFee,textView_totalAmout;

    TextView textView_sender;
    EditText editText_sender;
    TextInputEditText et_reference;
    Button button_topap;
    ImageView imageView_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topap_v2);

        session = getIntent().getStringExtra("session");
        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());

        editText_receiver = findViewById(R.id.editText_receiver);
        spinner_country = findViewById(R.id.spinner_country);
        textView_receiver = findViewById(R.id.textView_receiver);
        button_continue = findViewById(R.id.button_continue);
        textView_changeOperator = findViewById(R.id.textView_changeOperator);
        imageView_operator = findViewById(R.id.imageView_operator);
        spinner_value = findViewById(R.id.spinner_value);
        linear_operator = findViewById(R.id.linear_operator);
        linear_details = findViewById(R.id.linear_details);
        textView_amount = findViewById(R.id.textView_amount);
        textView_topapRate = findViewById(R.id.textView_topapRate);
        textView_serviceFee = findViewById(R.id.textView_serviceFee);
        textView_totalAmout = findViewById(R.id.textView_totalAmout);
        textView_sender = findViewById(R.id.textView_sender);
        editText_sender = findViewById(R.id.editText_sender);
        button_topap = findViewById(R.id.button_topap);
        et_reference = findViewById(R.id.et_reference);
        imageView_back = findViewById(R.id.imageView_back);

        imageView_back.setOnClickListener(this);
        button_continue.setOnClickListener(this);
        textView_changeOperator.setOnClickListener(this);
        button_topap.setOnClickListener(this);
        linear_operator.setVisibility(View.GONE);
        linear_details.setVisibility(View.GONE);
        spinnerNationality();
    }

    public void spinnerNationality() {
        try {
            JSONObject obj = new JSONObject(readJSONFromAsset());
            JSONArray array = obj.getJSONArray("country");

            ArrayList<String> list = new ArrayList<String>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject yeah = array.getJSONObject(i);
                list.add(yeah.getString("name"));
            }
            spinnerNationalityAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
            spinner_country.setTitle("Choose Country");
            spinner_country.setAdapter(spinnerNationalityAdapter);
            spinner_country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String spinner = parent.getItemAtPosition(position).toString();
                    try {
                        JSONObject obj = new JSONObject(readJSONFromAsset());
                        JSONArray array = obj.getJSONArray("country");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject yeah = array.getJSONObject(i);
                            if (spinner.equals("Israel")) {
                                Toast.makeText(getApplicationContext(), "COUNTRY NOT EXIST", Toast.LENGTH_SHORT).show();
                                Intent next = new Intent(getApplicationContext(), LoginActivity.class);
                                startActivity(next);
                            } else if (spinner.equals(yeah.getString("name"))) {
                                editText_receiver.setText("");
                                textView_receiver.setText(yeah.getString("dial_code"));
                                linear_operator.setVisibility(View.GONE);
                                linear_details.setVisibility(View.GONE);
//                                status_operator = false;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String readJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("countries.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_continue: {
                linear_operator.setVisibility(View.GONE);
                linear_details.setVisibility(View.GONE);
                if (editText_receiver.getText().toString().equals("")) {
                    editText_receiver.setError("Please enter mobile no");
                } else {
                    standardProgressDialog.show();
                    getOperator();
                }
                break;
            }

            case R.id.textView_changeOperator: {
                standardProgressDialog.show();
                openDialog();
                break;
            }

            case R.id.button_topap:{
                if(operatorId.equals("") || value.equals("")){
                    Toast.makeText(getApplicationContext(),"Operator not selected",Toast.LENGTH_SHORT).show();
                }else {
                    standardProgressDialog.show();
                    topap();
                }
                break;
            }

            case R.id.imageView_back:{
                onBackPressed();
                break;
            }
        }
    }

    private void openDialog() {
        linear_details.setVisibility(View.GONE);
        mBuilderOperator = new AlertDialog.Builder(TopapActivityV2.this, R.style.CustomDialog);
        final View mView = getLayoutInflater().inflate(R.layout.dialog_operator_v2, null);
        mBuilderOperator.setView(mView);
        mDialogOperator = mBuilderOperator.create();

        ImageView imageView_cancel = mView.findViewById(R.id.imageView_cancel);
        Spinner spinner_operator = mView.findViewById(R.id.spinner_operator);
        final Spinner spinner_value = mView.findViewById(R.id.spinner_value);

        imageView_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogOperator.dismiss();
            }
        });

        getOperatorChoose(mView,spinner_operator);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                mDialogOperator.show();
            }
        }, 1000);

    }

    public void getOperatorChoose(final View mView, final Spinner spinner_operator){
        Log.d("first","first");
        operatorNames=new ArrayList<>();
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"topup/"+countryId+"/operators",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            if(obj.has("operators")){
                                JSONArray arrOPerator = new JSONArray(obj.getString("operators"));
                                operatorNames.add("Please choose operator");
                                for(int i = 0; i <arrOPerator.length(); i++){
                                    JSONObject objOPP = arrOPerator.getJSONObject(i);
                                    operatorNames.add(objOPP.getString("operator"));
                                }
                                operatorOnselect(mView,spinner_operator);
                                spinner_operator.setAdapter(new ArrayAdapter<String>(mView.getContext(), android.R.layout.simple_spinner_dropdown_item, operatorNames));
                                standardProgressDialog.dismiss();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        final RequestQueue requestQueue = Volley.newRequestQueue(mView.getContext());
        requestQueue.add(stringRequest);
        requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
            @Override
            public void onRequestFinished(Request<Object> request) {
                requestQueue.getCache().clear();
            }
        });
    }


    public void operatorOnselect(final View mView, final Spinner spinner_operator){
        valueNames =new ArrayList<>();
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"topup/"+countryId+"/operators",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(final String response) {
                        standardProgressDialog.dismiss();
                        spinner_operator.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                String spinner = parent.getItemAtPosition(position).toString();
                                try {
                                    JSONObject obj = new JSONObject(response);
                                    if(obj.has("operators")){
                                        JSONArray arrOPerator = new JSONArray(obj.getString("operators"));
                                        for(int i = 0; i <arrOPerator.length(); i++){
                                            JSONObject objOPP = arrOPerator.getJSONObject(i);
                                            if(spinner.equals(objOPP.getString("operator"))){
                                                operatorId = objOPP.getString("operatorId");
                                                operator = objOPP.getString("operator");
                                                getSpinnerTopap();
                                            }
                                        }
                                    }
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }
                            }
                            public void onNothingSelected(AdapterView<?> parent) {
                            }
                        });
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        final RequestQueue requestQueue = Volley.newRequestQueue(mView.getContext());
        requestQueue.add(stringRequest);
        requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
            @Override
            public void onRequestFinished(Request<Object> request) {
                requestQueue.getCache().clear();
            }
        });
    }

    public void getSpinnerTopap(){
        mDialogOperator.dismiss();
        valueNames =new ArrayList<>();
        String mobileNo = textView_receiver.getText().toString() + "" + editText_receiver.getText().toString();
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING + "topup/operator/"+operatorId+"/product",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        Log.d("RESPONSE getTopap", response);
                        try {
                            JSONObject obj = new JSONObject(response);
                            linear_operator.setVisibility(View.VISIBLE);

                            operator = obj.getString("operator");
                            operatorId = obj.getString("operatorId");
                            countryId = obj.getString("countryId");
                            Picasso.get().load("https://fm.transfer-to.com:5443/logo_operator/logo-"+operatorId+"-2.png").into(imageView_operator);

                            JSONArray arrOPerator = new JSONArray(obj.getString("productList"));
                            valueNames.add("Please choose top up value in "+obj.getString("destinationCurrency"));
                            for(int i = 0; i <arrOPerator.length(); i++){
                                valueNames.add(arrOPerator.getString(i));
                            }
                            spinner_value.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, valueNames));
                            valueOnselect(spinner_value);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "Phone number error", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key", session);
                return headers;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    public void getOperator() {
        valueNames =new ArrayList<>();
        String mobileNo = textView_receiver.getText().toString() + "" + editText_receiver.getText().toString();
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING + "topup/" + mobileNo + "/product",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        Log.d("RESPONSE getTopap", response);
                        try {
                            JSONObject obj = new JSONObject(response);
                            linear_operator.setVisibility(View.VISIBLE);

                            operator = obj.getString("operator");
                            operatorId = obj.getString("operatorId");
                            countryId = obj.getString("countryId");
                            Picasso.get().load("https://fm.transfer-to.com:5443/logo_operator/logo-"+operatorId+"-2.png").into(imageView_operator);

                            JSONArray arrOPerator = new JSONArray(obj.getString("productList"));
                            valueNames.add("Please choose top up value in "+obj.getString("destinationCurrency"));
                            for(int i = 0; i <arrOPerator.length(); i++){
                                valueNames.add(arrOPerator.getString(i));
                            }
                            spinner_value.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, valueNames));
                            valueOnselect(spinner_value);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "Phone number error", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key", session);
                return headers;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    public void valueOnselect(final Spinner spinner_operator){
        spinner_operator.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                final String spinner = parent.getItemAtPosition(position).toString();
                Log.d("spinner",spinner);
                StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"topup/operator/"+operatorId+"/product",
                        new com.android.volley.Response.Listener<String>() {
                            @Override
                            public void onResponse(final String response) {
                                standardProgressDialog.dismiss();
                                try {
                                    JSONObject obj = new JSONObject(response);
                                    JSONArray arrs = new JSONArray(obj.getString("retailPriceList"));
                                    JSONArray who = new JSONArray(obj.getString("wholeSalePriceList"));
                                    destinationCurrency = obj.getString("destinationCurrency");
                                    JSONArray arrOPerator = new JSONArray(obj.getString("productList"));
                                    for(int i = 0; i <arrOPerator.length(); i++){
                                        if(spinner.equals(arrOPerator.getString(i))){
                                             value = spinner;
                                             retails_value = arrs.getString(i);
                                             whosale_price = who.getString(i);

                                            Log.d("value",value);
                                            Log.d("destinationCurrency",destinationCurrency);
                                            Log.d("retails_value",retails_value);

                                            linear_details.setVisibility(View.VISIBLE);
                                            textView_amount.setText(value+" "+destinationCurrency);
                                            textView_topapRate.setText(retails_value+"  MYR");
                                            textView_serviceFee.setText("0 MYR");
                                            textView_totalAmout.setText(retails_value+" MYR");
                                        }
                                    }
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }

                            }
                        },
                        new com.android.volley.Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                standardProgressDialog.dismiss();
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();

                        return params;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap();
                        headers.put("api-key",session);
                        return headers;
                    }
                };


                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                requestQueue.add(stringRequest);

            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });



    }

    public void topap(){
        if(operatorId.equals("")){
            Toast.makeText(getApplicationContext(),"Please choose operator",Toast.LENGTH_SHORT).show();
        }else{
            final String mobileNo = textView_receiver.getText().toString()+""+editText_receiver.getText().toString();

            StringRequest stringRequest = new StringRequest(POST, BasedUrl.URL_STAGING +"topup",
                    new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            standardProgressDialog.dismiss();

                            Toast.makeText(getApplicationContext(),"Transaction successful",Toast.LENGTH_SHORT).show();
                            Intent next = new Intent(getApplicationContext(), DashboardActivity.class);
                            next.putExtra("session",session);
                            startActivity(next);
                        }
                    },
                    new com.android.volley.Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            standardProgressDialog.dismiss();
                            parseVolleyError(error);
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("mobileNo",mobileNo);
                    params.put("senderMobileNo",textView_sender.getText().toString()+""+editText_sender.getText().toString());
                    params.put("product",value);
                    params.put("smscontent",et_reference.getText().toString());
                    params.put("operatorId",operatorId);
                    Log.d("param",params.toString());
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap();
                    headers.put("api-key",session);
                    return headers;
                }
            };
            int socketTimeout = 30000;
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            stringRequest.setRetryPolicy(policy);
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);

        }
    }

    public void parseVolleyError(VolleyError error) {
        try {
            String responseBody = new String(error.networkResponse.data, "utf-8");
            JSONObject data = new JSONObject(responseBody);
            if(data.has("message")){
                Toast.makeText(getApplicationContext(), data.getString("message"),Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
        } catch (UnsupportedEncodingException errorr) {
        }
    }
}
