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.WishListApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;

import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddElementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddElementFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private EditText nomElement, lienElement, adresseElement, prixElement, descriptionElement;
    private Button addEltButton, cancelButton;
    private ProgressDialog pg;

    // TODO: Rename and change types of parameters
    private int idParent;

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

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

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

    @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));
        }
        final View view = inflater.inflate(R.layout.fragment_add_element, container, false);
        nomElement = view.findViewById(R.id.elementTitle);
        lienElement = view.findViewById(R.id.elementLink);
        adresseElement = view.findViewById(R.id.elementAdresse);
        prixElement = view.findViewById(R.id.elementPrice);
        descriptionElement = view.findViewById(R.id.elementDescription);


        addEltButton = view.findViewById(R.id.addElement);
        addEltButton.setOnClickListener(v -> createElement());
        cancelButton = view.findViewById(R.id.cancelAddElement);
        cancelButton.setOnClickListener(v -> exitButton());
        return view;
    }



    public void exitButton() {
        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) -> returnToList(true));

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

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

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

    public void createElement() {
        onPreExecute();
        Double prixD;
        String prixS = prixElement.getText().toString();
        if (prixS == null || prixS.isEmpty()) {
            prixD = null;
        } else {
            try {
                prixD = Double.parseDouble(prixS);
            } catch (NumberFormatException e) {
                prixD = null;
            }
        }
        WishListApi.addElementToWishList(idParent, nomElement.getText().toString(), lienElement.getText().toString(), adresseElement.getText().toString(), prixD, descriptionElement.getText().toString(), new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                //response
                pg.dismiss();
                returnToList(true);
            }
        }, error -> {
            pg.dismiss();
            onError();
        });

    }

    public void returnToList(boolean appartient) {
        ((AppMainActivity) getActivity()).afficherContenuWishList(idParent, appartient);
    }

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






}
