package com.project.ilsaenterprise.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.adapter.ContactAdapter;
import com.project.ilsaenterprise.models.ContactModel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class ContactFragment extends Fragment {
    private DatabaseReference userRef;
    private String currentUser, userImageUrl;
    private FirebaseAuth mAuth;
    private static final int GalleryPick = 1;
    private StorageReference UserProfileImgRef;
    private View contactFragment;
    private List<ContactModel> contactList;
    private ListView contactLv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        contactFragment = inflater.inflate(R.layout.fragment_contact, container, false);

        contactList = new ArrayList<>();
        contactLv = contactFragment.findViewById(R.id.listViewContact);
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        UserProfileImgRef = FirebaseStorage.getInstance().getReference().child("profileImage");

        loadKontak();

        return contactFragment;
    }

    private void loadKontak(){
        userRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                contactList.clear();
                for (DataSnapshot ds : snapshot.getChildren()) {
                    ContactModel contactModel = ds.getValue(ContactModel.class);
                    contactList.add(contactModel);
                }

                Collections.reverse(contactList);
                ContactAdapter contactAdapter = new ContactAdapter(contactList, ContactFragment.this.getActivity());
                contactLv.setAdapter(contactAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getActivity().getApplicationContext(), "Download Error : " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
}