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.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
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.ContactAdapter;
import com.androiddev.project.ili.wishurgift.adapter.ContactPendingAdapter;
import com.androiddev.project.ili.wishurgift.adapter.ContactSearchAdapter;
import com.androiddev.project.ili.wishurgift.api.ContactsApi;
import com.androiddev.project.ili.wishurgift.api.UserApi;
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 ListeContactsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ListeContactsFragment extends Fragment {


    List<User> contactList = new ArrayList<>();
    List<User> contactRequestedList = new ArrayList<>();
    List<User> contactPendingList = new ArrayList<>();
    List<User> contactListFound = new ArrayList<>();
    ContactAdapter contactAdapter;
    ContactAdapter contactRequestedAdapter;
    ContactPendingAdapter contactPendingAdapter;
    ContactSearchAdapter contactFoundAdapter;
    private TextView addContactByTag;
    Gson gson = new Gson();
    private EditText zonesearchContacts;
    private ProgressDialog pg;

    public ListeContactsFragment() {
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ListeContacts.
     */
    // TODO: Rename and change types and number of parameters
    public static ListeContactsFragment newInstance() {
        ListeContactsFragment fragment = new ListeContactsFragment();
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @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_list_contacts, container, false);
        ListView listView = view.findViewById(R.id.myContactList);
        trouverContacts();
        contactAdapter = new ContactAdapter(getActivity(), contactList);
        listView.setAdapter(contactAdapter);
        ListView listView2 = view.findViewById(R.id.requestedContactList);
        trouverContactsRequested();
        contactRequestedAdapter = new ContactAdapter(getActivity(), contactRequestedList);
        listView2.setAdapter(contactRequestedAdapter);

        ListView listView3 = view.findViewById(R.id.pendingContactList);
        trouverContactsPending();
        contactPendingAdapter = new ContactPendingAdapter(getActivity(), contactPendingList);
        listView3.setAdapter(contactPendingAdapter);

        ListView listViewSearch = view.findViewById(R.id.myContactListFindBySearch);
        zonesearchContacts = view.findViewById(R.id.contactssearchbar);
        zonesearchContacts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchAllContacts(zonesearchContacts.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        contactFoundAdapter = new ContactSearchAdapter(getActivity(), contactListFound);
        listViewSearch.setAdapter(contactFoundAdapter);
        addContactByTag = view.findViewById(R.id.addContactList);
        addContactByTag.setOnClickListener(v -> afficherAjouterContacts());


        return view;
    }


    private void searchAllContacts(String texte) {
        if(!texte.isEmpty()) {
            UserApi.getUsersBySearchWithLimit(texte, 0, (Response.Listener<String>) response -> {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                    updateListeUserFoundBySearch(Arrays.asList(gson.fromJson(jsonArray.toString(), User[].class)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, error -> {
                onError();
            });
        } else{
            updateListeUserFoundBySearch(new ArrayList<>());
        }
    }

    private void updateListeUserFoundBySearch(List<User> newList) {
        contactListFound.clear();
        contactListFound.addAll(newList);
        contactFoundAdapter.notifyDataSetChanged();
    }

    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 trouverContacts() {
        onPreExecute();
        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)));
                pg.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }

    private void trouverContactsRequested() {
        ContactsApi.getContactsRequested((Response.Listener<String>) response -> {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                updateListeContactRequested(Arrays.asList(gson.fromJson(jsonArray.toString(), User[].class)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }

    private void trouverContactsPending() {
        ContactsApi.getContactsPending((Response.Listener<String>) response -> {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                updateListeContactPending(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);
        contactAdapter.notifyDataSetChanged();
    }

    private void updateListeContactPending(List<User> newList) {
        contactPendingList.clear();
        contactPendingList.addAll(newList);
        contactPendingAdapter.notifyDataSetChanged();
    }

    private void updateListeContactRequested(List<User> newList) {
        contactRequestedList.clear();
        contactRequestedList.addAll(newList);
        contactRequestedAdapter.notifyDataSetChanged();
    }

    public void afficherAjouterContacts() {
        ((AppMainActivity) getActivity()).afficherAjoutContact();
    }

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