package com.project.ilsaenterprise;

import android.Manifest;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

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

import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
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.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.google.zxing.WriterException;
import com.project.ilsaenterprise.account.CreateUser;
import com.project.ilsaenterprise.account.UserProfile;
import com.project.ilsaenterprise.models.Company;
import com.project.ilsaenterprise.models.Employees;
import com.project.ilsaenterprise.models.ModelNews;
import com.project.ilsaenterprise.services.NewsApi;
import com.project.ilsaenterprise.services.TimeUnits;
import com.project.manufacturing.Home;
import com.squareup.picasso.Picasso;
import com.thekhaeng.pushdownanim.PushDownAnim;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;

import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
import static android.content.Context.WINDOW_SERVICE;

public class Dashboard extends Fragment {

    private GridLayout mainGrid;
    private TextView nameText, dateView, greetView, tvDivision, tvFullname, tvPhone, tvNIP, tvEmail, tvJabatan,
            roleText, masukTxt, keluarTxt, hitungHadirTxt, locationTxt, judulBerita, jamBerita, tvGps;
    private ImageView imgBerita, ivLogo;
    private AnimatorSet animatorSet;
    private DatabaseReference userRef;
    private String currentUser, idPerusahaan;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;
    private static final String TAG = "ILSA";
    private static final int ERROR_DIALOG_REQUEST = 9001;
    private LocationManager locationManager;
    private double latitude, longitude;
    private ProgressBar mProgressBar;
    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 TextView country, currency, timestamp;
    private String kurs, ts;
    private BigDecimal bd;
    private Geocoder geocoder;
    private List<Address> addresses;
    private GoogleSignInAccount googleLogin;
    private QRGEncoder qrgEncoder;
    private ImageView qrImage;
    DatabaseReference companyRef;
    Dialog dialog;
    private AlertDialog loadDialog;
    private boolean gpsStatus;
    private AlertDialog.Builder builder;
    //private View shineAnim;
    //private LinearLayout btnClock;

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
//        getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getContext(), R.color.newDark));
        //View inflatedView = inflater.inflate(R.layout.activity_nav_button, container, false);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
        dialog = new Dialog(Dashboard.this.getContext());
        builder = new AlertDialog.Builder(Dashboard.this.getContext());

        mAuth = FirebaseAuth.getInstance();
        //currentUser = mAuth.getCurrentUser().getUid();
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        companyRef = FirebaseDatabase.getInstance().getReference("Company");

        swipeRefreshLayout = root.findViewById(R.id.refreshLayHome);
        TextView btnBacaSemua = root.findViewById(R.id.bacaSemuaBtn);
        judulBerita = root.findViewById(R.id.tvBerita);
        jamBerita = root.findViewById(R.id.tvJam);
        imgBerita = root.findViewById(R.id.ImgBerita);
//        tvNamaPerusahaan = root.findViewById(R.id.tvCompanyName);
        ivLogo = root.findViewById(R.id.ivCompanyLogo);
        tvFullname = root.findViewById(R.id.tvFullname);
        tvPhone = root.findViewById(R.id.tvHp);
        tvDivision = root.findViewById(R.id.tvDivision);
        tvNIP = root.findViewById(R.id.tvNIP);
        tvEmail = root.findViewById(R.id.tvEmail);
        tvJabatan = root.findViewById(R.id.tvJabatan);
        idPerusahaan = "";
        masukTxt = root.findViewById(R.id.masukTv);
        keluarTxt = root.findViewById(R.id.keluarTv);
        hitungHadirTxt = root.findViewById(R.id.countHadir);
        locationTxt = root.findViewById(R.id.lokasiHome);
        dateView = root.findViewById(R.id.jamText);
        tvGps = root.findViewById(R.id.tvGps);

        RelativeLayout btnAttendance = root.findViewById(R.id.btnAttendance);
        RelativeLayout btnHistory = root.findViewById(R.id.btnHistory);
        RelativeLayout btnWfh = root.findViewById(R.id.btnWfh);
        mProgressBar = root.findViewById(R.id.progress_bar);
        //qrImage = root.findViewById(R.id.ivQr);
//        btnClock = root.findViewById(R.id.btnClock);

        Calendar calDate = Calendar.getInstance();
        SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
        String currentDate = currentDateFormat.format(calDate.getTime());
        dateView.setText(currentDate);

        PushDownAnim.setPushDownAnimTo(btnAttendance).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocationPermission();
                if(isServicesOK()){
                    Intent intent = new Intent(Dashboard.this.getActivity(), MapActivity.class);
                    startActivity(intent);
                }
                else
                    Toast.makeText(Dashboard.this.getActivity().getBaseContext(), "Gagal menemukan lokasi", Toast.LENGTH_SHORT).show();
            }
        });

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

        PushDownAnim.setPushDownAnimTo(btnWfh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Dashboard.this.getActivity(), WorkFromHome.class);
                startActivity(intent);
                requireActivity().finish();
            }
        });

        PushDownAnim.setPushDownAnimTo(btnBacaSemua).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Dashboard.this.getActivity(), BeritaActivity.class);
                startActivity(intent);
                //getActivity().getFragmentManager().popBackStack();
            }
        });

        PushDownAnim.setPushDownAnimTo(judulBerita).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Dashboard.this.getActivity(), BeritaActivity.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() {
                        verifyUserExist();
                        getDeviceLocation();
                        loadJSON();

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

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

        return root;
    }

    private void verifyUserDevice(){
        String currentDevice = getDeviceName();
        Log.d("DEVICE ID", currentDevice);
        Log.d("UID", userFirebase.getUid());

        userRef.child(userFirebase.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(!snapshot.child("deviceId").exists()){
                    sendToSetting();
                }
                else if(!snapshot.child("deviceId").getValue().equals(currentDevice)){
                    Intent settingIntent = new Intent(Dashboard.this.getContext(), LoginBatal.class);
                    settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(settingIntent);
                }
                else
                    return;
            }

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

            }
        });

    }

    public String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    private String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    private void loadJSON() {
        mProgressBar.setMax(100);
        mProgressBar.setProgress(0);
        AndroidNetworking.get(NewsApi.GET_CATEGORY_BUSINESS)
                .setPriority(Priority.HIGH)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray playerArray = response.getJSONArray("articles");
                            for (int i = 0; i < 1; i++) {
                                JSONObject temp = playerArray.getJSONObject(i);
                                ModelNews dataApi = new ModelNews();
                                judulBerita.setText(temp.getString("title"));
                                jamBerita.setText(TimeUnits.getTimeAgo(temp.getString("publishedAt")));
                                String retrieveImg = temp.getString("urlToImage");
                                Picasso.get().load(retrieveImg).placeholder(R.drawable.placeholder_news).into(imgBerita);
                                mProgressBar.setVisibility(View.GONE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(Dashboard.this.getContext(), "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(ANError anError) {
                        mProgressBar.setVisibility(View.GONE);
//                        Toast.makeText(Dashboard.this.getContext(), "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @SuppressLint("NewApi")
    private void generateQr(){
        String inputValue = userFirebase.getUid();
        Bitmap bitmap;
        if (inputValue.length() > 0) {
            WindowManager manager = (WindowManager) getActivity().getSystemService(WINDOW_SERVICE);
            Display display = manager.getDefaultDisplay();
            Point point = new Point();
            display.getSize(point);
            int width = point.x;
            int height = point.y;
            int smallerDimension = width < height ? width : height;
            smallerDimension = smallerDimension * 3 / 4;

            qrgEncoder = new QRGEncoder(
                    inputValue, null,
                    QRGContents.Type.TEXT,
                    smallerDimension);
            try {
                bitmap = qrgEncoder.encodeAsBitmap();
                qrImage.setImageBitmap(bitmap);
            } catch (WriterException e) {
                Log.v(TAG, e.toString());
            }
        } else {
            return;
        }
    }

    private void getDeviceLocation(){

        Geocoder geocoder = new Geocoder(Dashboard.this.getContext(), Locale.getDefault());

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        try{
            if(mLocationPermissionsGranted){
                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) {
                                try {
                                    addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(),1);
                                    Log.d("INFOOOO", currentLocation.getLatitude() + " " + currentLocation.getLongitude());
                                    if(addresses != null){

                                        locationTxt.setText(addresses.get(0).getAddressLine(0));
                                    }
                                    else {
                                        locationTxt.setText("Lokasi tidak ditemukan");
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            else
                                getDeviceLocation();
                        } else{
                            Toast.makeText(getActivity().getBaseContext(), "Pencarian Titik Gagal", Toast.LENGTH_SHORT).show();
                            mFusedLocationProviderClient.getLastLocation();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "SecurityException: " + e.getMessage() );
        }
    }

    private void activeGpsDialog(){
        dialog.setContentView(R.layout.layout_gps_permission);
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button btnIjin = dialog.findViewById(R.id.btnIjin);

        btnIjin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public void checkGps(){
        locationManager = (LocationManager) Dashboard.this.requireContext().getSystemService(Context.LOCATION_SERVICE);
        assert locationManager != null;
        gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Log.d("GPSSSSSSSSSSS", String.valueOf(gpsStatus));
        if(gpsStatus) {
            tvGps.setText(R.string.gps_on);
        }
        else{
            tvGps.setText(R.string.gps_off);
        }
    }

//    @Override
//    public void onLocationChanged(Location location) {
//        getDeviceLocation();
//    }
//
//    @Override
//    public void onStatusChanged(String provider, int status, Bundle extras) {
//
//    }
//
//    @Override
//    public void onProviderEnabled(String provider) {
//
//    }
//
//    @Override
//    public void onProviderDisabled(String provider) {
//
//    }

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

        return currentDate;
    }


    private void getCountHari(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("history");
        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 String getDate(long time) {
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        int day = cal.getTime().getDay();
        int month = cal.getTime().getMonth() + 1;

        StringBuilder timeBuilder = new StringBuilder();

        if(day == 1)
            timeBuilder.append("Senin, ");
        else if(day == 2)
            timeBuilder.append("Selasa, ");
        else if(day == 3)
            timeBuilder.append("Rabu, ");
        else if(day == 4)
            timeBuilder.append("Kamis, ");
        else if(day == 5)
            timeBuilder.append("Jumat, ");
        else if(day == 6)
            timeBuilder.append("Sabtu, ");
        else if(day == 7)
            timeBuilder.append("Minggu, ");

        timeBuilder.append(cal.getTime().getDate());

        if(month == 1)
            timeBuilder.append(" Januari");
        else if(month == 2)
            timeBuilder.append(" Februari");
        else if(month == 3)
            timeBuilder.append(" Maret");
        else if(month == 4)
            timeBuilder.append(" April");
        else if(month == 5)
            timeBuilder.append(" Mei");
        else if(month == 6)
            timeBuilder.append(" Juni");
        else if(month == 7)
            timeBuilder.append(" Juli");
        else if(month == 8)
            timeBuilder.append(" Agustus");
        else if(month == 9)
            timeBuilder.append(" September");
        else if(month == 10)
            timeBuilder.append(" Oktober");
        else if(month == 11)
            timeBuilder.append(" November");
        else if(month == 12)
            timeBuilder.append(" Desember");

        timeBuilder.append(cal.getTime().getYear());
        //timeBuilder.append(cal.getTime().getTime());

        return timeBuilder.toString();
    }

    private String getTime(long time) {
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(time);
        int hour = cal.getTime().getHours();
        int minute = cal.getTime().getMinutes();
        int second = cal.getTime().getSeconds();
        int day = cal.getTime().getDay();
        String dayString = "";

        if(day == 1)
            dayString = "Senin, ";
        else if(day == 2)
            dayString = "Selasa, ";
        else if(day == 3)
            dayString = "Rabu, ";
        else if(day == 4)
            dayString = "Kamis, ";
        else if(day == 5)
            dayString = "Jumat, ";
        else if(day == 6)
            dayString = "Sabtu, ";
        else if(day == 7)
            dayString = "Minggu, ";

        return dayString + hour + ' ' + ':' + ' ' + minute + ' ' + ':' + ' ' + second;
    }

    private void getMasuk(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("attendance");
        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 void getKeluar(){
        DatabaseReference attRef = FirebaseDatabase.getInstance().getReference("attendance");
        String mAuth = FirebaseAuth.getInstance().getCurrentUser().getUid();

        attRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Log.d("TESSTT", "1");
                if(snapshot.hasChild(getCurrentDate())){
                    Log.d("TESSTT", "2");
                    if(snapshot.child(getCurrentDate()).hasChild("Check Out")){
                        Log.d("TESSTT", "3");
                        if(snapshot.child(getCurrentDate()).child("Check Out").hasChild(mAuth)){
                            Log.d("TESSTT", "4");
                            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 void retrieveData() {

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

                tvDivision.setText(employees.getDivisi());
                tvFullname.setText(employees.getNamaLengkap());
                tvJabatan.setText(employees.getJabatan());
                tvEmail.setText(employees.getEmail());
                tvNIP.setText(employees.getNip());
                tvPhone.setText(employees.getNoHp());
                idPerusahaan = employees.getPerusahaan();
            }

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

        companyRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(idPerusahaan == null)
                    startActivity(new Intent(Dashboard.this.getContext(), CreateUser.class));
                else
                {
                    Company company = snapshot.child(idPerusahaan).getValue(Company.class);
                    //tvNamaPerusahaan.setText(company.getNama());
                    Picasso.get().load(company.getLogo()).into(ivLogo);
                }
            }

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

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        getLocationPermission();
        checkGps();
        new getBackgroundTask().execute();

//        getLocation();
//        loadJSON();
    }



    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();
        new getBackgroundTask().execute();
        //new GetKurs().execute();

//        getLocation();
//        loadJSON();
    }


//    private void shiningBtn(){
//        Animation animation = AnimationUtils.loadAnimation(HomeFragment.this.getContext(), R.anim.anim_shine);
//        shineAnim.startAnimation(animation);
//
//        animation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                shineAnim.startAnimation(animation);
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void verifyUserExist() {
        //String currentUID = mAuth.getCurrentUser().getUid();

        userRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if ((snapshot.child(userFirebase.getUid()).exists())) {
                    retrieveData();
                    getMasuk();
                    getKeluar();
                    getCountHari();
//                    getLocation();
//                    loadJSON();
                } else{
                    sendToSetting();
                }

            }

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

            }
        });
    }

    private void sendToSetting() {

//        Intent settingIntent = new Intent(getActivity(), UserProfile.class);
//        settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        startActivity(settingIntent);
//        getActivity().finish();
    }

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

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

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

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

    private class getBackgroundTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            locationTxt.setText(R.string.RefreshStr);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            userFirebase = mAuth.getCurrentUser();
            googleLogin = GoogleSignIn.getLastSignedInAccount(Dashboard.this.requireContext());
            if(userFirebase != null){
                verifyUserExist();
                verifyUserDevice();
                //generateQr();
            }
            else{
                Toast.makeText(Dashboard.this.getContext(), "User tidak tersedia", Toast.LENGTH_SHORT).show();
            }
            getDeviceLocation();
            loadJSON();

            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);

        }
    }

//    private class GetKurs extends AsyncTask<Void, Void, Void> {
//        @Override
//        protected void onPreExecute() {
//            super.onPreExecute();
//            country.setText(R.string.RefreshStr);
//        }
//
//        @Override
//        protected Void doInBackground(Void... arg0) {
//            HttpHandler sh = new HttpHandler();
//
//            String jsonStr = sh.makeServiceCall(KursApi.Currency_JSON);
//
//            if (jsonStr != null) {
//                try {
//                    JSONObject jsonObj = new JSONObject(jsonStr);
//
//                    JSONObject kursObj = jsonObj.getJSONObject("rates");
//                    kurs = kursObj.getString("IDR");
//                    ts = jsonObj.getString("timestamp");
//                } catch (final JSONException e) {
//                    Log.e("KURS", "Json parsing error: " + e.getMessage());
//                }
//
//            } else {
//                Log.e("KURS", "Couldn't get json from server.");
//
//            }
//
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Void result) {
//            super.onPostExecute(result);
//            country.setText("IDR");
//            bd = BigDecimal.valueOf(Double.parseDouble(kurs)).setScale(2, RoundingMode.HALF_UP);
//            currency.setText(kurs);
//            timestamp.setText(getDate(Long.parseLong(bd)));
//        }
//    }

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