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 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.ShareUserAdapter;
import com.androiddev.project.ili.wishurgift.api.ContactsApi;
import com.androiddev.project.ili.wishurgift.api.WishListApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.User;
import com.google.gson.Gson;

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

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShareListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShareListFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    List<User> contactList = new ArrayList<>();
    ShareUserAdapter shareUserAdapter;
    Gson gson = new Gson();
    private int wishlistParentId;
    private ProgressDialog pg;

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

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

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

        }
    }

    @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_share_list, container, false);
        getListItems();
        ListView listView = view.findViewById(R.id.userList);
        shareUserAdapter = new ShareUserAdapter(getActivity(), contactList);
        listView.setAdapter(shareUserAdapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            User selectedItem = (User) parent.getItemAtPosition(position);
            partagerListe(selectedItem);
        });

        return view;
    }

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


    private void partagerListe(User selectedItem) {
        WishListApi.shareWishList(wishlistParentId, selectedItem.getId(), response -> {
            ((AppMainActivity) getActivity()).afficherContenuWishList(wishlistParentId, true);
        }, error -> {
            onError();
        });
    }

    private void getListItems() {
        ContactsApi.getContacts((Response.Listener<String>) response -> {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                updateListeContact(Arrays.asList(gson.fromJson(jsonArray.toString(), User[].class)));

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


    private void updateListeContact(List<User> newList) {
        contactList.clear();
        contactList.addAll(newList);
        shareUserAdapter.notifyDataSetChanged();
    }

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