package com.project.ilsaenterprise;

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

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

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 java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class QuestWfh extends AppCompatActivity {
    private static final String TAG = "Location";
    TextView tvDay, tvLoc, tvMonth;
    private LocationManager locationManager;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    Task location;
    private static final int ERROR_DIALOG_REQUEST = 9001;
    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 static Location currentLocation;
    private RecyclerView rvMainTask;


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

        initialization();
        getLocationPermission();
        getDeviceLocation();
        currentDate();
    }

    private void getStaggered(){
//        rvMainTask.setAdapter(new TaskAdapter(bitmaps));
        StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvMainTask.setLayoutManager(mLayoutManager);
    }

    private void initialization(){
        tvDay = findViewById(R.id.tvDayWfh);
        tvMonth = findViewById(R.id.tvMonthWfh);
        tvLoc = findViewById(R.id.tvLocationWfh);
        rvMainTask = findViewById(R.id.rvMainTask);
    }

    private void getDeviceLocation(){
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        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();

                            Geocoder geocoder = new Geocoder(getBaseContext(), 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);
                            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 currentDate(){
        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());
        tvDay.setText(day);
        tvMonth.setText(month);
    }

    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);
        }
    }

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

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

}