package com.project.ilsaenterprise.monitoring;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
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.project.ilsaenterprise.R;
import com.project.ilsaenterprise.adapter.MonitoringAdapter;
import com.project.ilsaenterprise.models.MonitoringListModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class HistoryMonitoring extends AppCompatActivity {
    private ArrayList<MonitoringListModel> postList;
    private RecyclerView listMonitoringView;
    private ArrayList<String> listMonitoring = new ArrayList<>();
    private FirebaseAuth mAuth;
    private String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
    private DatabaseReference ref = FirebaseDatabase.getInstance().getReference("monitoring");
    private String cUser;
    private RelativeLayout relNoList;
    private DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
    private MonitoringAdapter monitoringAdapter;
    private MonitoringAdapter.onItemClickListener clickListener;
    private GoogleSignInAccount googleLogin;
    private LinearLayout layPlaceholder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.Dark));
        setContentView(R.layout.activity_history_monitoring);
        getSupportActionBar().hide();

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());

        mAuth = FirebaseAuth.getInstance();
        cUser = mAuth.getCurrentUser().getUid();
        relNoList = findViewById(R.id.relNoList);
        postList = new ArrayList<>();
        loadPost();
    }

    private void InitializeFields() {
        setClickListener();
        listMonitoringView = findViewById(R.id.listHistoryMonitoring);
        monitoringAdapter = new MonitoringAdapter(postList, clickListener, HistoryMonitoring.this);
        listMonitoringView.setLayoutManager(new LinearLayoutManager(HistoryMonitoring.this, LinearLayoutManager.VERTICAL, false));
        listMonitoringView.setAdapter(monitoringAdapter);
    }

    private void setClickListener(){
        clickListener = new MonitoringAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TextView currentGroupName = view.findViewById(R.id.idMonitoring);
                String idMonitoring = currentGroupName.getText().toString();
                TextView dilihatTxt = view.findViewById(R.id.countSee);
                ref.child(idMonitoring).child("listLihat").child(cUser).setValue(true);

                Intent groupChatIntent = new Intent(HistoryMonitoring.this, ShowSelfMonitoring.class);
                groupChatIntent.putExtra("idMonitoring", idMonitoring);
                startActivity(groupChatIntent);
            }
        };
    }

    private void loadPost() {
        ProgressBar progressBar = findViewById(R.id.pbHistoryMonitoring);
        layPlaceholder = findViewById(R.id.layPlaceholder);
        progressBar.setVisibility(View.VISIBLE);

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                postList.clear();
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    MonitoringListModel modelPost = ds.getValue(MonitoringListModel.class);
                    if(modelPost.getUid().equals(cUser))
                    {
                        Log.d("MASUK", modelPost.getUid());
                        long jlhLihat = dataSnapshot.child(modelPost.getTimestamp()).child("listLihat").getChildrenCount();
                        long jlhComment = dataSnapshot.child(modelPost.getTimestamp()).child("komentar").getChildrenCount();

                        modelPost.setCountSee(jlhLihat);
                        modelPost.setCountComment(jlhComment);
                        long tmp = Long.parseLong(modelPost.getTimestamp());
                        modelPost.setDateUpload(getDate(tmp));

                        userRef.child(modelPost.getUid()).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot snapshot) {
                                String username = snapshot.child("namaLengkap").getValue(String.class);
                                String role = snapshot.child("role").getValue(String.class);
                                String userImg = snapshot.child("image").getValue(String.class);
                                String jabatan = snapshot.child("jabatan").getValue(String.class);
                                modelPost.setFullName(username);
                                modelPost.setRole(role);
                                modelPost.setImgLink(userImg);
                                modelPost.setJabatan(jabatan);
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError error) {

                            }
                        });

                        postList.add(modelPost);
                    }
                    else
                        continue;
                }
                Collections.reverse(postList);
                if(postList.size() == 0)
                    relNoList.setVisibility(View.VISIBLE);
                final Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        layPlaceholder.setVisibility(View.GONE);
                        InitializeFields();
                    }
                }, 1000);
                progressBar.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(HistoryMonitoring.this, ""+databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });


    }

    private String getDate(long time) {
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(time);
        String clock = cal.getTime().getHours() + ":" + cal.getTime().getMinutes();
        String date = "";

        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);

        if(month == 0)
            date += day + " Januari " + year;
        if(month == 1)
            date += day + " Februari " + year;
        if(month == 2)
            date += day + " Maret " + year;
        if(month == 3)
            date += day + " April " + year;
        if(month == 4)
            date += day + " Mei " + year;
        if(month == 5)
            date += day + " Juni " + year;
        if(month == 6)
            date += day + " Juli " + year;
        if(month == 7)
            date += day + " Agustus " + year;
        if(month == 8)
            date += day + " September " + year;
        if(month == 9)
            date += day + " Oktober " + year;
        if(month == 10)
            date += day + " November " + year;
        if(month == 11)
            date += day + " Desember " + year;

        return clock + " | " + date;
    }
}