package com.maxmoney.maxcddconsole.Activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
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.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
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.Calendar;
import java.util.HashMap;
import java.util.Map;

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

public class RegistrationActivity extends AppCompatActivity {

    StandardProgressDialog standardProgressDialog;
    LinearLayout linear_dob,linear_nric,linear_passport;
    EditText editText_email,editText_fullname,editText_dob,editText_nric,editText_passport,editText_address,editText_city,
            editText_postalCode,editText_mobile;
    Spinner spinner_state;
    SearchableSpinner spinner_nationality;
    Button button_register;
    RadioGroup radioGroup_accType,radioGroup_idType;
    TextWatcher tw;
    ArrayAdapter<String> spinnerNationalityAdapter;
    String nationality = "",session ="";
    RadioButton radioButton_passport,radioButton_nric,radioButton_personal,radioButton_business;
    ImageView imageView_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);

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

        linear_dob = findViewById(R.id.linear_dob);
        linear_nric = findViewById(R.id.linear_nric);
        linear_passport = findViewById(R.id.linear_passport);

        editText_email = findViewById(R.id.editText_email);
        editText_fullname = findViewById(R.id.editText_fullname);
        editText_dob = findViewById(R.id.editText_dob);
        editText_nric = findViewById(R.id.editText_nric);
        editText_passport = findViewById(R.id.editText_passport);
        editText_address = findViewById(R.id.editText_address);
        editText_city = findViewById(R.id.editText_city);
        editText_postalCode = findViewById(R.id.editText_postalCode);
        editText_mobile = findViewById(R.id.editText_mobile);

        radioGroup_accType = findViewById(R.id.radioGroup_accType);
        radioGroup_idType = findViewById(R.id.radioGroup_idType);

        radioButton_passport = findViewById(R.id.radioButton_passport);
        radioButton_nric = findViewById(R.id.radioButton_nric);
        radioButton_personal = findViewById(R.id.radioButton_personal);
        radioButton_business = findViewById(R.id.radioButton_business);

        spinner_state = findViewById(R.id.spinner_state);
        spinner_nationality = findViewById(R.id.spinner_nationality);
        button_register = findViewById(R.id.button_register);

        imageView_back = findViewById(R.id.imageView_back);

        radioButton_passport.setEnabled(false);
        radioButton_nric.setEnabled(false);
        radioButton_personal.setEnabled(false);
        radioButton_business.setEnabled(false);


        button_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText_email.getText().toString().equals("")){
                    editText_email.setError("Please fill the value");
                }else if(editText_fullname.getText().toString().equals("")){
                    editText_fullname.setError("Please fill the value");
                }else if(editText_fullname.getText().toString().equals("")){
                    editText_fullname.setError("Please fill the value");
                }else if(editText_address.getText().toString().equals("")){
                    editText_address.setError("Please fill the value");
                }else if(editText_city.getText().toString().equals("")){
                    editText_city.setError("Please fill the value");
                }else if(editText_postalCode.getText().toString().equals("")){
                    editText_postalCode.setError("Please fill the value");
                }else{
                    RegisterCustomer();
                }
            }
        });

        imageView_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        spinnerNationality();
        editText_dob.addTextChangedListener(tw);
    }

    @NonNull
    private TextWatcher ValidationBirthday() {
        return new TextWatcher() {
            private String current = "";
            private String ddmmyyyy = "DDMMYYYY";
            private Calendar cal = Calendar.getInstance();
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().equals(current)) {
                    String clean = s.toString().replaceAll("[^\\d.]|\\.", "");
                    String cleanC = current.replaceAll("[^\\d.]|\\.", "");
                    int cl = clean.length();
                    int sel = cl;
                    for (int i = 2; i <= cl && i < 6; i += 2) {
                        sel++;
                    }
                    if (clean.equals(cleanC)) sel--;
                    if (clean.length() < 8) {
                        clean = clean + ddmmyyyy.substring(clean.length());
                    } else {
                        int day = Integer.parseInt(clean.substring(0, 2));
                        int mon = Integer.parseInt(clean.substring(2, 4));
                        int year = Integer.parseInt(clean.substring(4, 8));
                        mon = mon < 1 ? 1 : mon > 12 ? 12 : mon;
                        cal.set(Calendar.MONTH, mon - 1);
                        year = (year < 1900) ? 1900 : (year > 2100) ? 2100 : year;
                        cal.set(Calendar.YEAR, year);
                        day = (day > cal.getActualMaximum(Calendar.DATE)) ? cal.getActualMaximum(Calendar.DATE) : day;
                        clean = String.format("%02d%02d%02d", day, mon, year);
                    }
                    clean = String.format("%s-%s-%s", clean.substring(0, 2),
                            clean.substring(2, 4),
                            clean.substring(4, 8));
                    sel = sel < 0 ? 0 : sel;
                    current = clean;
                    editText_dob.setText(current);
                    editText_dob.setSelection(sel < current.length() ? sel : current.length());
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        };
    }

    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_nationality.setTitle("Choose Country");
            spinner_nationality.setAdapter(spinnerNationalityAdapter);
            spinner_nationality.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"))){
                                nationality = yeah.getString("nationality");
                                Log.d("Nationality",nationality);

                                if(nationality.equals("Malaysian")){
                                    linear_dob.setVisibility(View.GONE);
                                    linear_passport.setVisibility(View.GONE);
                                    linear_nric.setVisibility(View.VISIBLE);
                                    radioButton_nric.setChecked(true);
                                    radioButton_personal.setChecked(true);
                                }else{
                                    linear_dob.setVisibility(View.VISIBLE);
                                    linear_passport.setVisibility(View.VISIBLE);
                                    linear_nric.setVisibility(View.GONE);
                                    radioButton_passport.setChecked(true);
                                    radioButton_personal.setChecked(true);
                                }
                            }
                        }
                    }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;
    }

    public void RegisterCustomer(){
        standardProgressDialog.show();
        StringRequest stringRequest = new StringRequest(POST, BasedUrl.URL_STAGING +"customers",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(),"Customer Register",Toast.LENGTH_SHORT).show();

                        Intent next = new Intent(getApplicationContext(),CddActivity.class);
                        next.putExtra("customerName",editText_fullname.getText().toString());
                        next.putExtra("email",editText_email.getText().toString());
                        if(nationality.equals("Malaysian")){
                            next.putExtra("idNo",editText_nric.getText().toString());
                            next.putExtra("idType","NRIC");
                        }else{
                            next.putExtra("idNo",editText_passport.getText().toString());
                            next.putExtra("idType","Passport");
                        }
                        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("customerName",editText_fullname.getText().toString());
                params.put("email",editText_email.getText().toString());
                params.put("mobile",editText_mobile.getText().toString());
                params.put("address",editText_address.getText().toString());
                params.put("city",editText_city.getText().toString());
                params.put("postalCode",editText_postalCode.getText().toString());
                params.put("country","Malaysia");
                params.put("idExpiryDate","31-12-2100");

                if(spinner_state.getSelectedItem().toString().toUpperCase().equals("KUALA LUMPUR")){
                    params.put("state","KUALA_LUMPUR");
                }else if(spinner_state.getSelectedItem().toString().toUpperCase().equals("NEGERI SEMBILAN")){
                    params.put("state","KUALA_LUMPUR");
                }else{
                    params.put("state",spinner_state.getSelectedItem().toString().toUpperCase());
                }

                params.put("nationalityCountry",spinner_nationality.getSelectedItem().toString());

                if(nationality.equals("Malaysian")){
                    params.put("nationality",nationality);
                    params.put("idType","NRIC");
                    params.put("type","Individual");
                    params.put("idNo",editText_nric.getText().toString());
                }else{
                    params.put("nationality",nationality);
                    params.put("idType","Passport");
                    params.put("type","Individual");
                    params.put("idNo",editText_passport.getText().toString());
                    params.put("dob",editText_dob.getText().toString());
                }
                return params;
            }
        };
        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);
            Toast.makeText(getApplicationContext(),data.getString("description"),Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
        } catch (UnsupportedEncodingException errorr) {
        }
    }

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