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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

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.adapter.ElementAdapter;
import com.androiddev.project.ili.wishurgift.api.WishListApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.Element;
import com.androiddev.project.ili.wishurgift.model.WishListContent;
import com.google.gson.Gson;

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

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WishListContentFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WishListContentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WishListContentFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ElementAdapter elementAdapter;
    private List<Element> elements = new ArrayList<>();
    private TextView addElement;
    private TextView shareWishList;
    Gson gson = new Gson();
    private ProgressDialog pg;

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

    public WishListContentFragment() {
        // 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 WishListContentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WishListContentFragment newInstance(int param1, boolean param2) {
        WishListContentFragment fragment = new WishListContentFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putBoolean(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);
            appartient = getArguments().getBoolean(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(Wishurgift.getSessionVariables().getUserConnected()==null || Wishurgift.getSessionVariables().getToken()==null){
            getActivity().finish();
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
        View view = inflater.inflate(R.layout.fragment_wish_list_content, container, false);
        setVisibleAppartient(view);
        ListView listView = view.findViewById(R.id.myListContent);
        elementAdapter = new ElementAdapter(getActivity(), elements, appartient, idParent);
        listView.setAdapter(elementAdapter);
        afficherDonnees();
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            Element selectedItem = (Element) parent.getItemAtPosition(position);
            afficherDetail(selectedItem);
        });

        return view;
    }

    public void setVisibleAppartient(View view) {
        if (appartient) {
            addElement = view.findViewById(R.id.addElementButton);
            addElement.setOnClickListener(v -> afficherAjouterWishlist());
            addElement.setVisibility(View.VISIBLE);
            shareWishList = view.findViewById(R.id.shareButton);
            shareWishList.setOnClickListener(v -> afficherShareWishList());
        }
    }

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


    public void afficherDonnees() {
        WishListApi.getWishListById(idParent, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONObject jsonData = jsonObject.getJSONObject("data");
                afficherDonneesWishListContent(gson.fromJson(jsonData.toString(), WishListContent.class));

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

    public void afficherDonneesWishListContent(WishListContent content) {
        TextView name = getView().findViewById(R.id.wishlistName);
        TextView stats = getView().findViewById(R.id.statsWishlistContent);
        elements.clear();
        elements.addAll(content.getElements());
        Log.d("log", "" + elements.size());
        name.setText(content.getName());
        stats.setText("Total : " + content.getStats().getTotal() + " Unbuy : " + content.getStats().getUnbuy());
        elementAdapter.notifyDataSetChanged();
        if (content.getIs_public() && appartient) {
            shareWishList.setVisibility(View.VISIBLE);
        }
        Log.d("log", "updated");
    }

    public void afficherAjouterWishlist() {
        ((AppMainActivity) getActivity()).afficherAjouterElement(idParent);

    }

    public void afficherDetail(Element elt) {

        ((AppMainActivity) getActivity()).afficherElement(idParent, elt.getId(), appartient);

    }

    private void afficherShareWishList() {

        ((AppMainActivity) getActivity()).afficherShareList(idParent);

    }

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

