package com.project.ilsaenterprise.monitoring;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.project.ilsaenterprise.Dashboard;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.models.Beacon;
import com.project.ilsaenterprise.models.Channel;

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

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import pl.pawelkleczkowski.customgauge.CustomGauge;

public class MainBeacon extends AppCompatActivity {
    //====================
    private TextView tvHumidity, tvTemperature, tvPressure, tvWindSpeed, tvWindDirection, tvChannelId, tvLastEntry, tvFeed, tvTotal, btnShow, tvLocation, tvStatus;
    //====================
    private static final String JSON_URL = "https://api.thingspeak.com/channels/1603955/feeds.json?api_key=ND0HG1CVKUENHMZQ&results=1";
    private ImageView ivWeather;
    private List<Address> addresses;
    private AlertDialog alertDialog;
    private AlertDialog.Builder dialogBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_beacon);
        getSupportActionBar().hide();

        dialogBuilder = new AlertDialog.Builder(MainBeacon.this);
        alertDialog = dialogBuilder.create();
        showProgress(R.layout.layout_loading);

        tvHumidity = findViewById(R.id.tvHumidity);
        tvTemperature = findViewById(R.id.tvTemperature);
        tvPressure = findViewById(R.id.tvPressure);
        tvWindSpeed = findViewById(R.id.tvSpeed);
        tvWindDirection = findViewById(R.id.tvDirection);
        tvChannelId = findViewById(R.id.tvChannelID);
        tvLastEntry = findViewById(R.id.tvLastEntry);
        tvFeed = findViewById(R.id.tvFeed);
        tvTotal = findViewById(R.id.tvTotalData);
        btnShow = findViewById(R.id.btnShow);
        tvLocation = findViewById(R.id.tvLocation);
        ivWeather = findViewById(R.id.ivWeather);
        tvStatus = findViewById(R.id.tvStatus);

        long date = System.currentTimeMillis();
        SimpleDateFormat adf = new SimpleDateFormat("kk");
        String hourString = adf.format(date);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int h = metrics.heightPixels;
        int w = metrics.widthPixels;

        Log.d("JAMM", hourString);

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainBeacon.this, ShowData.class));
            }
        });

        loadData();
    }

    private void showProgress(int layout){
        View layoutView = getLayoutInflater().inflate(layout, null);
        dialogBuilder.setView(layoutView);
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    private void loadData(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL, new Response.Listener<String>(){
            @Override
            public void onResponse(String response){

                try {
                    JSONObject obj = new JSONObject(response);
                    JSONArray sensorArray = obj.getJSONArray("feeds");

                    Log.d("REQQ", obj.getJSONObject("channel").getString("id"));

//                    for (int i = sensorArray.length() - 1; i >= 0; i--) {
//                    }
                    JSONObject arrayObject = sensorArray.getJSONObject(sensorArray.length() - 1);
//                    JSONObject sensorObject2 = sensorArray.getJSONObject(sensorArray.length()-1);
                    //String parseLembab = String.valueOf(Math.round(Float.parseFloat(sensorObject.getString("field1"))));

                    Channel channelDetail = new Channel(Long.parseLong(obj.getJSONObject("channel").getString("id")), obj.getJSONObject("channel").getString("name"),
                            obj.getJSONObject("channel").getString("latitude"), obj.getJSONObject("channel").getString("longitude"), obj.getJSONObject("channel").getString("field1"),
                            obj.getJSONObject("channel").getString("field2"), obj.getJSONObject("channel").getString("field3"), obj.getJSONObject("channel").getString("field4"),
                            obj.getJSONObject("channel").getString("field5"), obj.getJSONObject("channel").getString("field6"), obj.getJSONObject("channel").getString("field7"),
                            obj.getJSONObject("channel").getString("field8"), obj.getJSONObject("channel").getString("created_at"), obj.getJSONObject("channel").getString("updated_at"),
                            obj.getJSONObject("channel").getString("last_entry_id"));
                    Beacon beaconData = new Beacon(arrayObject.getString("created_at"), arrayObject.getString("entry_id"), arrayObject.getString("field1"), arrayObject.getString("field2"), arrayObject.getString("field3"),
                            arrayObject.getString("field4"), arrayObject.getString("field5"), arrayObject.getString("field6"), arrayObject.getString("field7"), arrayObject.getString("field8"));

                    tvTemperature.setText(beaconData.getTemperature());
                    tvHumidity.setText(beaconData.getHumidity());
                    tvPressure.setText(beaconData.getPressure());
                    tvWindSpeed.setText(beaconData.getWind_speed());
                    tvWindDirection.setText(beaconData.getWind_direction());
                    tvChannelId.setText(String.valueOf(channelDetail.getId()));
                    tvLastEntry.setText(setLocalGMT(beaconData.getCreated_at()));
                    tvFeed.setText("8");
                    tvTotal.setText(channelDetail.getLast_entry_id());



                    getDeviceLocation(Double.parseDouble(channelDetail.getLatitude()), Double.parseDouble(channelDetail.getLongitude()));
                    alertDialog.cancel();
//                    ListViewAdapter adapter = new ListViewAdapter(sensorList, getApplicationContext());
//
//                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occur
                        Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());

        //adding the string request to request queue
        requestQueue.add(stringRequest);
    }

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

    private String setLocalGMT(String time){
        StringBuilder sb = new StringBuilder();
        String timeAgo = "";
        String[] result = new String[6];

        String[] date = time.replace("T", "-")
                .replace("Z", "-")
                .replace(":", "-")
                .split("-");

        Log.d("HARIII", date[0]);

        int year = Integer.parseInt(date[0]);
        int month = Integer.parseInt(date[1]);
        int day = Integer.parseInt(date[2]);
        int hour = Integer.parseInt(date[3]) + 7;
        int minute = Integer.parseInt(date[4]);
        int second = Integer.parseInt(date[5]);

        DecimalFormat formatter = new DecimalFormat("00");
        sb.append(formatter.format(day));
        sb.append(" ");
        sb.append(getMonth(month));
        sb.append(" ");
        sb.append(formatter.format(year));
        sb.append(" | ");
        sb.append(formatter.format(hour));
        sb.append(":");
        sb.append(formatter.format(minute));
        sb.append(":");
        sb.append(formatter.format(second));

        return sb.toString();
    }

    private String getMonth(int m){
        if(m == 1)
            return "Januari";
        if(m == 2)
            return "Februari";
        if(m == 3)
            return "Maret";
        if(m == 4)
            return "April";
        if(m == 5)
            return "Mei";
        if(m == 6)
            return "Juni";
        if(m == 7)
            return "Juli";
        if(m == 8)
            return "Agustus";
        if(m == 9)
            return "September";
        if(m == 10)
            return "Oktober";
        if(m == 11)
            return "November";
        if(m == 12)
            return "Desember";

        return "";
    }

    private void getDeviceLocation(double latitude, double longitude){

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

        try {
            addresses = geocoder.getFromLocation(latitude, longitude,1);
            tvLocation.setText(addresses.get(0).getAddressLine(0));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}