package com.project.ilsaenterprise;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.models.Employees;
import com.thekhaeng.pushdownanim.PushDownAnim;

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

public class WorkFromHome extends AppCompatActivity {
    private TextView nameText, dateView, greetView, jabatanText, namaLengkapText, kebunText, nikText, totPegawai, roleText, masukTxt, keluarTxt, hitungHadirTxt, tvDay, tvLoc, tvMonth, tvDate;
    private DatabaseReference userRef;
    //private String currentUser;
    //private FirebaseAuth mAuth;
    private static final String TAG = "ILSA";
    private static final int ERROR_DIALOG_REQUEST = 9001;
    private DatabaseReference checkAttendance;
    private Task location;
    private Location currentLocation;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private Boolean mLocationPermissionsGranted = false;
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Boolean deviceLocated = false;
    private GoogleSignInAccount googleLogin;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;

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

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

        Calendar calDate = Calendar.getInstance();
        SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd MMMM yyyy");
        String currentDate = currentDateFormat.format(calDate.getTime());
        checkAttendance = FirebaseDatabase.getInstance().getReference("attendance").child(currentDate);
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        CardView btnWfh = findViewById(R.id.btnAttendance);
        swipeRefreshLayout = findViewById(R.id.refreshLay);

//        dateView = (TextView) findViewById(R.id.dateWfh);
        greetView = (TextView) findViewById(R.id.greeting_text);
//        dateView.setText(currentDate);
        Date dt = new Date();
        int hours = dt.getHours();
        int min = dt.getMinutes();

        if(hours>=0 && hours<=11){
            greetView.setText("Selamat Pagi");
        }else if(hours>=11 && hours<=15 && min > 0){
            greetView.setText("Selamat Siang");
        }else if(hours>=15 && hours<=18 && min > 0){
            greetView.setText("Selamat Sore");
        }else if(hours>=18 && hours<=24 && min > 0){
            greetView.setText("Selamat Malam");
        }

        nameText = (TextView) findViewById(R.id.text_user);
        namaLengkapText = (TextView) findViewById(R.id.tvFullname);
        jabatanText = (TextView) findViewById(R.id.tvJabatan);
        kebunText = (TextView) findViewById(R.id.tvDivision);
        nikText = (TextView) findViewById(R.id.tvNIP);
        roleText = (TextView) findViewById(R.id.tvPhone);
        masukTxt = findViewById(R.id.masukTv);
        keluarTxt = findViewById(R.id.keluarTv);
        hitungHadirTxt = findViewById(R.id.countHadir);
        tvDay = findViewById(R.id.tvDayWfh);
        tvMonth = findViewById(R.id.tvMonthWfh);
        tvDate = findViewById(R.id.tvDateWfh);
        tvLoc = findViewById(R.id.tvLoc);

        //retrieveData();
        getKeluar();
        getMasuk();
        getCountHari();
        showCurrentDate();
        getDeviceLocation();

        CardView btnHistory = findViewById(R.id.history_btnwfh);
        CardView btnAddTodos = findViewById(R.id.list_btnWfh);
        CardView btnSendData = findViewById(R.id.send_btnWfh);

        if(isServicesOK()){
            PushDownAnim.setPushDownAnimTo(btnWfh).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkAttendance.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            if(snapshot.hasChild("Check In")){
                                if(snapshot.child("Check In").hasChild(userFirebase.getUid())){
                                    Toast.makeText(getBaseContext(), "Anda tidak sedang WFH", Toast.LENGTH_LONG).show();
                                }
                            }
                            else {
                                Intent intent = new Intent(WorkFromHome.this, AttendanceWfh.class);
                                startActivity(intent);
                            }
                        }

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

                        }
                    });
                }
            });
        }
        else
            isServicesOK();

        PushDownAnim.setPushDownAnimTo(btnHistory).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkFromHome.this, CheckKehadiranWfh.class);
                startActivity(intent);
            }
        });

        PushDownAnim.setPushDownAnimTo(btnAddTodos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkFromHome.this, QuestWfh.class);
                startActivity(intent);
            }
        });

        PushDownAnim.setPushDownAnimTo(btnSendData).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkFromHome.this, KirimData.class);
                startActivity(intent);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                final Handler setDelay = new Handler();
                setDelay.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //retrieveData();
                        getKeluar();
                        getMasuk();
                        getCountHari();
                        getDeviceLocation();

                        if(deviceLocated = false)
                            Toast.makeText(getBaseContext(), "Koordinat Perangkat tidak ditemukan", Toast.LENGTH_SHORT).show();

                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 2000);
                //========
            }
        });
    }

    private void getLocationPermission(){
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            {
                mLocationPermissionsGranted = true;
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    private void getDeviceLocation(){
        getLocationPermission();

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        try{
            if(mLocationPermissionsGranted){
                //&& task.getResult() != null
                location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful() && task.getResult() != null){
                            currentLocation = (Location) task.getResult();

                            if (currentLocation != null) {
                                Geocoder geocoder = new Geocoder(WorkFromHome.this, Locale.getDefault());
                                List<Address> addresses = null;
                                try {
                                    addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(),1);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                String address = addresses.get(0).getAddressLine(0);

                                if(address != null){
                                    tvLoc.setText(address);
                                    deviceLocated = true;
                                }
                                else {
                                    tvLoc.setText("Lokasi tidak ditemukan");
                                }
                            }

                        } else{
//                            Toast.makeText(getBaseContext(), "Pencarian Titik Gagal", Toast.LENGTH_SHORT).show();
                            mFusedLocationProviderClient.getLastLocation();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void showCurrentDate(){
        Calendar calDate = Calendar.getInstance();
        SimpleDateFormat currentDay = new SimpleDateFormat("dd");
        SimpleDateFormat currentMonth = new SimpleDateFormat("MMMM");
        String day = currentDay.format(calDate.getTime());
        String month = currentMonth.format(calDate.getTime());
        getDay();
        tvDay.setText(day);
        tvMonth.setText(month);
    }

    private void getDay(){
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_WEEK);

        switch (day) {
            case Calendar.SUNDAY:
                tvDate.setText("Minggu");
                break;
            case Calendar.MONDAY:
                tvDate.setText("Senin");
                break;
            case Calendar.TUESDAY:
                tvDate.setText("Selasa");
                break;
            case Calendar.WEDNESDAY:
                tvDate.setText("Rabu");
                break;
            case Calendar.THURSDAY:
                tvDate.setText("Kamis");
                break;
            case Calendar.FRIDAY:
                tvDate.setText("Jumat");
                break;
            case Calendar.SATURDAY:
                tvDate.setText("Sabtu");
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(WorkFromHome.this, Home.class));
        finish();
    }


    private void getMasuk(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("attendanceWFH");
        String mAuth = FirebaseAuth.getInstance().getCurrentUser().getUid();

        attRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.hasChild(getCurrentDate())){
                    if(snapshot.child(getCurrentDate()).hasChild("Check In")){
                        if(snapshot.child(getCurrentDate()).child("Check In").hasChild(mAuth)){
                            long time = Long.parseLong(snapshot.child(getCurrentDate()).child("Check In").child(mAuth).child("time").getValue().toString());
                            masukTxt.setText(getTime(time));
                        }
                    }
                }
                else
                    return;
            }

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

            }
        });
    }

    private String getCurrentDate(){
        Calendar calDate = Calendar.getInstance();
        SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd MMMM yyyy");
        String currentDate = currentDateFormat.format(calDate.getTime());

        return currentDate;
    }


    private void getCountHari(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("historyWFH");
        String mAuth = FirebaseAuth.getInstance().getCurrentUser().getUid();

        attRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.hasChild(mAuth)){
                    int hari = 0;
                    for(DataSnapshot ds : snapshot.child(mAuth).getChildren()){
                        if(ds.child("keterangan").getValue().equals("Keluar"))
                            hari++;
                        else
                            continue;
                    }

                    hitungHadirTxt.setText(String.valueOf(hari));
                }
                else
                    return;
            }

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

            }
        });
    }


    private void getKeluar(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("attendanceWFH");
        String mAuth = FirebaseAuth.getInstance().getCurrentUser().getUid();

        attRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.hasChild(getCurrentDate())){
                    if(snapshot.child(getCurrentDate()).hasChild("Check Out")){
                        if(snapshot.child(getCurrentDate()).child("Check Out").hasChild(mAuth)){
                            long time = Long.parseLong(snapshot.child(getCurrentDate()).child("Check Out").child(mAuth).child("time").getValue().toString());
                            keluarTxt.setText(getTime(time));
                        }
                    }
                }
            }

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

            }
        });
    }

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

    public boolean isServicesOK(){
        int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(WorkFromHome.this);

        if(available == ConnectionResult.SUCCESS){
            return true;
        }
        else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
            Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(WorkFromHome.this, available, ERROR_DIALOG_REQUEST);
            dialog.show();
        }else{
            Toast.makeText(WorkFromHome.this, "You can't make map requests", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private void retrieveData(){

        userRef.child(userFirebase.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Employees employees = dataSnapshot.getValue(Employees.class);

                nikText.setText(employees.getNoPeg());
                nameText.setText(employees.getNamaLengkap());
                namaLengkapText.setText(employees.getNamaLengkap());
                jabatanText.setText(employees.getJabatan());
                kebunText.setText(employees.getAlamat());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
    }
}