CreateEvent.java 9.02 KB
package net.plil.clubinfo.etunicorn.app.event;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import net.plil.clubinfo.etunicorn.R;
import net.plil.clubinfo.etunicorn.app.MainActivity;
import net.plil.clubinfo.etunicorn.utils.VolleyUtils;

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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class CreateEvent extends DialogFragment {

    private DialogInterface.OnDismissListener onDismissListener;


    Calendar myCalendar = Calendar.getInstance();


    EditText mName;
    EditText mPrice;
    Spinner mDate;

    TextInputLayout mPriceInput;
    TextInputLayout mNameInput;
    ProgressBar mProgressBar;
    private String[] arraySpinnerDate;
    private ArrayAdapter<String> adapterDate;
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_create_event, null);
        mName = (EditText) view.findViewById(R.id.create_event_name);
        mPrice = (EditText) view.findViewById(R.id.create_event_price);
        mDate = (Spinner) view.findViewById(R.id.create_event_date);
        mPriceInput = (TextInputLayout) view.findViewById(R.id.create_event_price_input);
        mNameInput = (TextInputLayout) view.findViewById(R.id.create_event_name_input);
        arraySpinnerDate = new String[]{
                getString(R.string.create_event_date_input)
        };
        adapterDate = new ArrayAdapter<>(getActivity(),
                R.layout.simple_item_layout, arraySpinnerDate);
        mDate.setAdapter(adapterDate);

        mProgressBar = (ProgressBar) view.findViewById(R.id.create_event_progress_bar);
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.create_event)
                .setView(view)
                .setPositiveButton(R.string.valid, null)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        VolleyUtils.getInstance(getContext()).getRequestQueue().cancelAll(CreateEvent.class);
                    }
                }).create();

        mDate.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    new DatePickerDialog(getContext(), date, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                }
                return true;
            }
        });

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean testDateInputOk = true;
                        if (mPrice.getText().toString().isEmpty()) {
                            mPriceInput.setError(getString(R.string.error_create_event_input_price));
                            testDateInputOk = false;
                        } else {
                            mPriceInput.setError(null);
                        }
                        if (mName.getText().toString().isEmpty()) {
                            mNameInput.setError(getString(R.string.error_create_event_input_nom));
                            testDateInputOk = false;
                        } else {
                            mNameInput.setError(null);
                        }
                        if ((mDate.getSelectedItem()).equals(getString(R.string.create_event_date))) {
                            testDateInputOk = false;
                            Toast.makeText(getContext(), getString(R.string.error_create_event_date), Toast.LENGTH_LONG).show();
                        }
                        if (testDateInputOk) {
                            mProgressBar.setVisibility(View.VISIBLE);
                            mPriceInput.setVisibility(View.GONE);
                            mNameInput.setVisibility(View.GONE);
                            mDate.setVisibility(View.GONE);
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("nom", mName.getText().toString());
                                jsonObject.put("prix", Double.parseDouble(mPrice.getText().toString()));
                                jsonObject.put("date", mDate.getAdapter().getItem(0));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, VolleyUtils.baseUri + "/evenement", jsonObject, new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    mProgressBar.setVisibility(View.GONE);
                                    dismiss();
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    mProgressBar.setVisibility(View.GONE);
                                    mPriceInput.setVisibility(View.VISIBLE);
                                    mNameInput.setVisibility(View.VISIBLE);
                                    mDate.setVisibility(View.VISIBLE);
                                    Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            }
                            ) {
                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    Map<String, String> headers = new HashMap<>();
                                    headers.put("Authorization", MainActivity.session.getToken());
                                    return headers;
                                }
                            };
                            jsonObjectRequest.setTag(CreateEvent.class);
                            VolleyUtils.getInstance(getContext()).addToRequestQueue(jsonObjectRequest);
                        }
                    }
                });
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    @Override
    public void onStop() {
        VolleyUtils.getInstance(getContext()).getRequestQueue().cancelAll(CreateEvent.class);
        dismissAllowingStateLoss();
        super.onStop();
    }

    private void updateLabel() {
        String myFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
        arraySpinnerDate[0] = sdf.format(myCalendar.getTime());
        adapterDate.notifyDataSetChanged();
    }

    public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (onDismissListener != null) {
            onDismissListener.onDismiss(dialog);
        }
    }

}