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.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.project.ilsaenterprise.adapter.AttendanceAdapter;
import com.project.ilsaenterprise.models.Attendance;
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 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 HistoryAttendance extends AppCompatActivity {

    private static final String TAG = "History Attendance";
    private ListView listView;
    private List<Attendance> historyList;
    private LinearLayout backHeader;
    private static String workPos, strPos;
    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());
    private RelativeLayout relNoList;
    private GoogleSignInAccount googleLogin;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;
    ArrayList<Double> locationList = new ArrayList<Double>();
    private AttendanceAdapter attendanceAdapter;

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

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        mAuth = FirebaseAuth.getInstance();
        userFirebase = mAuth.getCurrentUser();

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

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

    }

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

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("history").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.setDate(getDate(Long.parseLong(modelPost.getTime())));
                    modelPost.setTime(getTime(Long.parseLong(modelPost.getTime())));
                    locationList.add(Double.parseDouble(modelPost.getLat()));
                    locationList.add(Double.parseDouble(modelPost.getLng()));
                    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);
                attendanceAdapter = new AttendanceAdapter(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(HistoryAttendance.this, "Data Error" + databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void refreshPage(){
        finish();
        startActivity(new Intent(this, HistoryAttendance.class));
    }

    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(" dd MMMM yyyy", cal).toString();
        return date;
    }

    private String getTime(long time) {
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        String date = DateFormat.format("kk : mm : ss", cal).toString();
        return date;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK));
    }
}
