package com.project.ilsaenterprise;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.adapter.AttendanceAdapter;
import com.project.ilsaenterprise.adapter.HistoryWfhAdapter;
import com.project.ilsaenterprise.models.Attendance;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CheckKehadiranWfh extends AppCompatActivity {

    private static final String TAG = "History Attendance";
    private ListView listView;
    private List<Attendance> historyList;
    private FirebaseAuth mAuth;
    private RelativeLayout relNoList;
    private LinearLayout backHeader;
    private String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
    private DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("users")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());

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

        listView = findViewById(R.id.listView);
        relNoList = findViewById(R.id.relNoList);
        backHeader = findViewById(R.id.header);
        historyList = new ArrayList<>();

        backHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CheckKehadiranWfh.this, WorkFromHome.class));
                finish();
            }
        });

        loadHistory();
    }

    private void loadHistory() {
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        FirebaseUser user = mAuth.getInstance().getCurrentUser();
        final String userID = user.getUid();

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("historyWFH").child(userID);

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                historyList.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Attendance modelPost = ds.getValue(Attendance.class);
                    modelPost.setTime(getDate(Long.parseLong(modelPost.getTime())));
                    modelPost.setStrLoc(getLoc(modelPost.getLat(), modelPost.getLng()));
                    modelPost.setLat(modelPost.getLat() + (char) 0x00B0 + " E");
                    modelPost.setLng(modelPost.getLng() + (char) 0x00B0 + " N");
                    historyList.add(modelPost);
                }
                Collections.reverse(historyList);
                HistoryWfhAdapter attendanceAdapter = new HistoryWfhAdapter(historyList, getApplicationContext());
                listView.setAdapter(attendanceAdapter);
                if(historyList.size() == 0)
                    relNoList.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.INVISIBLE);
            }

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

    private String getLoc(String Lat, String Lng){
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(Double.parseDouble(Lat), Double.parseDouble(Lng),1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String address = addresses.get(0).getAddressLine(0);

        return address;
    }

    private String getDate(long time) {
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        String date = DateFormat.format(" HH:mm aaa, dd MMMM yyyy", cal).toString();
        return date;
    }
}