package com.maxmoney.maxcddconsole.Activity;

import android.content.Intent;
import android.media.Image;
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.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;
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 TopapActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView imageView_back;
    SearchableSpinner spinner_country;
    EditText editText_receiver,editText_sender;
    TextView textView_receiver,textView_sender;
    Button button_operator,button_topap;
    TextInputEditText et_reference;
    String session = "",operatorId="",retails_value = "",value="",whosale_price ="",destinationCurrency="";
    StandardProgressDialog standardProgressDialog;
    ArrayAdapter<String> spinnerNationalityAdapter;
    LinearLayout linear_sender,linear_reference;
    AlertDialog.Builder mBuilderOperator;
    AlertDialog mDialogOperator;
    ArrayList<String> operatorNames;
    ArrayList<String> valueNames;
    boolean status_operator = false;
    String current_topap_operator = "",current_operator_id="";
    TextView textView_amount,textView_topapRate,textView_serviceFee,textView_totalAmout;
    LinearLayout linear_details;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topap);

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

        imageView_back = findViewById(R.id.imageView_back);
        spinner_country = findViewById(R.id.spinner_country);
        editText_receiver = findViewById(R.id.editText_receiver);
        editText_sender = findViewById(R.id.editText_sender);
        textView_receiver = findViewById(R.id.textView_receiver);
        textView_sender = findViewById(R.id.textView_sender);
        button_operator = findViewById(R.id.button_operator);
        button_topap = findViewById(R.id.button_topap);
        et_reference = findViewById(R.id.et_reference);
        linear_sender = findViewById(R.id.linear_sender);
        linear_reference = findViewById(R.id.linear_reference);

        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);

        linear_details.setVisibility(View.GONE);
        imageView_back.setOnClickListener(this);
        button_operator.setOnClickListener(this);
        button_topap.setOnClickListener(this);
        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"));
                                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() {
        Intent next = new Intent(getApplicationContext(),DashboardActivity.class);
        next.putExtra("session",session);
        startActivity(next);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case  R.id.imageView_back: {
                onBackPressed();
                break;
            }
            case R.id.button_operator: {
                if(editText_receiver.getText().toString().equals("")){
                    editText_receiver.setError("Please insert value");
                }else{
                    getTopapProduct();
                }
                break;
            }

            case R.id.button_topap: {
                if(status_operator){
                    if(editText_receiver.getText().toString().equals("")){
                        Toast.makeText(getApplicationContext(),"Please insert sender phone num and choose operator",Toast.LENGTH_SHORT).show();
                    }else{
                        standardProgressDialog.show();
                        topap();
                    }

                }else if(status_operator == false){
                    Toast.makeText(getApplicationContext(),"Please choose operator first",Toast.LENGTH_SHORT).show();
                }else if(editText_receiver.getText().toString().equals("")){
                    Toast.makeText(getApplicationContext(),"Please insert sender phone num and choose operator",Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

    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());

                    if(operatorId.equals("")){
                        params.put("operatorId",current_operator_id);
                    }else {
                        params.put("operatorId",operatorId);
                    }


                    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 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) {
        }
    }


    public void getTopapProduct(){
        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 ",response);
                        try {
                            JSONObject obj = new JSONObject(response);
                            current_topap_operator = obj.getString("operator");
                            current_operator_id = obj.getString("operatorId");
                            showDialogOperator(obj.getString("countryId"));
                        } 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;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    private void showDialogOperator(String countryId) {
        mBuilderOperator = new AlertDialog.Builder(TopapActivity.this, R.style.CustomDialog);
        final View mView = getLayoutInflater().inflate(R.layout.dialog_operator, null);
        mBuilderOperator.setView(mView);
        mDialogOperator = mBuilderOperator.create();
        mDialogOperator.show();

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

        imageView_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogOperator.dismiss();
                status_operator = false;
                linear_details.setVisibility(View.GONE);
            }
        });

        button_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogOperator.dismiss();
                status_operator = true;
                linear_details.setVisibility(View.VISIBLE);
            }
        });

        getOperator(mView,spinner_operator,countryId,spinner_value);
    }

    public void getOperator(final View mView, final Spinner spinner_operator, final String countryId, final Spinner spinner_value){
        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) {
                        standardProgressDialog.dismiss();
                        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,countryId,spinner_value);
                                }
                                spinner_operator.setAdapter(new ArrayAdapter<String>(mView.getContext(), android.R.layout.simple_spinner_dropdown_item, operatorNames));
                                spinner_operator.setSelection(getIndex(spinner_operator, current_topap_operator));
                                getSpinnerValue(mView,spinner_value,current_operator_id);
                                Log.d("current_operator_id",current_operator_id);
                            }
                        } 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 operatorOnselect(final View mView, final Spinner spinner_operator, final String countryId, final Spinner spinner_value){
        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");

                                                 getSpinnerValue(mView,spinner_value,operatorId);
                                                 Log.d("operatorId",operatorId);
                                             }
                                        }
                                     }
                                }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;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    public void getSpinnerValue(final View mView, final Spinner spinner_value, String operatorId){
        valueNames =new ArrayList<>();
        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();
                        try {
                            JSONObject obj = new JSONObject(response);
                            if(obj.has("productList")){
                                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));
                                }
                                valueOnselect(mView,spinner_value,spinner_value);
                                spinner_value.setAdapter(new ArrayAdapter<String>(mView.getContext(), android.R.layout.simple_spinner_dropdown_item, valueNames));
                            }
                        } 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 valueOnselect(final View mView, final Spinner spinner_operator, final Spinner spinner_value){
        if(operatorId.equals("")){
            operatorId = current_operator_id;
        }
        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();
                        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("productList")){
                                        JSONArray arrOPerator = new JSONArray(obj.getString("productList"));
                                        for(int i = 0; i <arrOPerator.length(); i++){
                                            if(spinner.equals(arrOPerator.getString(i))){
                                                JSONArray arrs = new JSONArray(obj.getString("retailPriceList"));
                                                JSONArray who = new JSONArray(obj.getString("wholeSalePriceList"));
                                                value = spinner;
                                                retails_value = arrs.getString(i);
                                                whosale_price = who.getString(i);
                                                destinationCurrency = obj.getString("destinationCurrency");

                                                textView_amount.setText(value+" "+destinationCurrency);
                                                textView_topapRate.setText(retails_value+" "+destinationCurrency);
                                                textView_serviceFee.setText("0 MYR");
                                                textView_totalAmout.setText(retails_value+" "+destinationCurrency);


                                            }
                                        }
                                    }
                                }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;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }


    private int getIndex(Spinner spinner, String myString){
        for (int i=0;i<spinner.getCount();i++){
            if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
                return i;
            }
        }
        return 0;
    }
}
