package com.androiddev.project.ili.wishurgift.fragments;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.fragment.app.Fragment;

import com.android.volley.Response;
import com.androiddev.project.ili.wishurgift.R;
import com.androiddev.project.ili.wishurgift.activities.AppMainActivity;
import com.androiddev.project.ili.wishurgift.activities.LoginActivity;
import com.androiddev.project.ili.wishurgift.api.ElementsApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.Element;
import com.google.gson.Gson;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EditElementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EditElementFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private int idParent, idElt;
    private EditText newNameElement, newLinkElement, newAddressElement, newPriceElement, newDescriptionElement;
    private Button saveUpdateElement, cancelEditElement;

    Gson gson = new Gson();
    private ProgressDialog pg;
    private boolean appartient;

    public EditElementFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment EditElementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EditElementFragment newInstance(int param1, int param2) {
        EditElementFragment fragment = new EditElementFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idParent = getArguments().getInt(ARG_PARAM1);
            idElt = getArguments().getInt(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(Wishurgift.getSessionVariables().getUserConnected()==null || Wishurgift.getSessionVariables().getToken()==null){
            getActivity().finish();
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
        View view = inflater.inflate(R.layout.fragment_edit_element, container, false);


        newNameElement = view.findViewById(R.id.newNameElement);
        newLinkElement = view.findViewById(R.id.newLinkElement);
        newAddressElement = view.findViewById(R.id.newAddressElement);
        newPriceElement = view.findViewById(R.id.newPriceElement);
        newDescriptionElement = view.findViewById(R.id.newDescriptionElement);

        saveUpdateElement = view.findViewById(R.id.saveUpdateElement);
        saveUpdateElement.setOnClickListener(v -> updateElement());
        cancelEditElement = view.findViewById(R.id.cancelEditElement);
        cancelEditElement.setOnClickListener(v -> cancelEditElement());
        return view;
    }

    protected void onPreExecute() {
        pg = new ProgressDialog(getContext(), R.style.AppTheme_Dark_Dialog);
        pg.setTitle("Processing...");
        pg.setMessage("Please wait.");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }

    private void updateElement() {
        Double prixD;
        String prixS = newPriceElement.getText().toString();
        if (prixS == null || prixS.isEmpty()) {
            prixD = null;
        } else {
            try {
                prixD = Double.parseDouble(prixS);
            } catch (NumberFormatException e) {
                prixD = null;
            }
        }
        onPreExecute();
        ElementsApi.updateElement(idElt, newNameElement.getText().toString(), newLinkElement.getText().toString(), newAddressElement.getText().toString(), prixD, newDescriptionElement.getText().toString(), response -> {
            pg.dismiss();
            afficherElement();
        }, error -> {
            pg.dismiss();
            onError();
        });

    }

    private void afficherElement() {
        onPreExecute();
        ElementsApi.getElementByID(idElt, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                Element elt = gson.fromJson(jsonObject.getJSONObject("data").toString(), Element.class);
                newNameElement.setText(elt.getName());
                newLinkElement.setText(elt.getLink());
                newAddressElement.setText(elt.getAddress());
                newPriceElement.setText(String.valueOf(elt.getPrice()));
                newDescriptionElement.setText(elt.getDescription());
                pg.dismiss();
                ((AppMainActivity) getActivity()).afficherElement(idParent, idElt, appartient);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }


    /**
     * gestion cancel
     */

    public void cancelEditElement() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
        // Setting Alert Dialog Title
        alertDialogBuilder.setTitle("Confirm exit");
        // Icon Of Alert Dialog
        //alertDialogBuilder.setIcon(R.drawable.question);
        // Setting Alert Dialog Message
        alertDialogBuilder.setMessage("Are you sure you want to exit");
        alertDialogBuilder.setCancelable(false);

        alertDialogBuilder.setPositiveButton("Yes", (arg0, arg1) -> ((AppMainActivity) getActivity()).afficherElement(idParent, idElt, appartient));

        alertDialogBuilder.setNegativeButton("No", (dialog, which) -> dialog.cancel());

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public void onError(){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("An error has occured");
        alertDialogBuilder.setMessage("You will be redirected to the login page").setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                Wishurgift.getSessionVariables().setUserConnected(null);
                Wishurgift.getSessionVariables().setToken(null);
                ((AppMainActivity)getActivity()).finish();
                getActivity().startActivity(new Intent(getContext(), LoginActivity.class));
            }
        });
        AlertDialog alertDialog =alertDialogBuilder.create();
        alertDialog.show();
    }
}
