package com.example.meteo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Gravity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.preference.PreferenceManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.meteo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements FetchData.AsyncResponse {

    public LastMeasurement lastMeasurement = null;
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private SwipeRefreshLayout swipeRefresh;

    /** processFinish,
     * Overrides method from async task (Fetch data)
     * Result from async task from method onPostExecute(result) is received here
     * input parameter lastMeasurement contains received data */
    @Override
    public void processFinish(LastMeasurement lastMeasurement)
    {
        //Here you will receive the result fired from async class
        //of onPostExecute(result) method.
        int toast_duration = Toast.LENGTH_SHORT;

        if(lastMeasurement != null)
        {
            this.lastMeasurement = lastMeasurement;

            Toast toast = Toast.makeText(getApplicationContext(), R.string.toast_updated, toast_duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            updateView(true);
        }
        else
        {
            Toast toast = Toast.makeText(getApplicationContext(), R.string.toast_not_updated, toast_duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            updateView(false);
        }
        // Disable refresh icon
        swipeRefresh.setRefreshing(false);
    }

    /** updateView,
     * Update text in views on main meteo screen
     * input parameter updated determines whether the data is valid or not */
    public void updateView(boolean updated)
    {
        TextView textView;

        if(updated)
        {
            SimpleDateFormat dateTimeFormat = new SimpleDateFormat(getResources().getString(R.string.date_time_format), Locale.getDefault());

            textView = findViewById(R.id.textViewName);
            textView.setText(String.valueOf(lastMeasurement.name));

            textView = findViewById(R.id.textViewTimestamp);
            textView.setText(dateTimeFormat.format(lastMeasurement.timestamp));
            textView.setBackgroundColor(getResources().getColor(R.color.gray_table_row));

            textView = findViewById(R.id.textViewTemperature);
            textView.setText(String.valueOf(lastMeasurement.temperature));

            textView = findViewById(R.id.textViewDewPoint);
            textView.setText(String.valueOf(lastMeasurement.dewPoint));

            textView = findViewById(R.id.textViewTemperatureFeelsLike);
            textView.setText(String.valueOf(lastMeasurement.temperatureFeelsLike));

            textView = findViewById(R.id.textViewHumidity);
            textView.setText(String.valueOf(lastMeasurement.humidity));

            textView = findViewById(R.id.textViewPressure);
            textView.setText(String.valueOf(lastMeasurement.pressure));

            textView = findViewById(R.id.textViewSeaLevelPressure);
            textView.setText(String.valueOf(lastMeasurement.seaLevelPressure));

            textView = findViewById(R.id.textViewWindSpeed);
            textView.setText(String.valueOf(lastMeasurement.windSpeed));

            textView = findViewById(R.id.textViewWindAngleStr);
            textView.setText(lastMeasurement.windAngleStr);

            textView = findViewById(R.id.textViewRainAmount5M);
            textView.setText(String.valueOf(lastMeasurement.rainAmount5M));

            textView = findViewById(R.id.textViewRainAmount24H);
            textView.setText(String.valueOf(lastMeasurement.rainAmount24H));

            textView = findViewById(R.id.textViewRainAmount7D);
            textView.setText(String.valueOf(lastMeasurement.rainAmount7D));

            textView = findViewById(R.id.textViewUvIndex);
            textView.setText(String.valueOf(lastMeasurement.uvIndex));

            textView = findViewById(R.id.textViewSoilTemp1);
            textView.setText(String.valueOf(lastMeasurement.soilTemp1));

            textView = findViewById(R.id.textViewSoilTempDepth1);
            textView.setText(lastMeasurement.soilTempDepth1);

            textView = findViewById(R.id.textViewSoilTemp2);
            textView.setText(String.valueOf(lastMeasurement.soilTemp2));

            textView = findViewById(R.id.textViewSoilTempDepth2);
            textView.setText(lastMeasurement.soilTempDepth2);

            textView = findViewById(R.id.textViewSoilTemp3);
            textView.setText(String.valueOf(lastMeasurement.soilTemp3));

            textView = findViewById(R.id.textViewSoilTempDepth3);
            textView.setText(lastMeasurement.soilTempDepth3);

            textView = findViewById(R.id.textViewSoilMoisture1);
            textView.setText(String.valueOf(lastMeasurement.soilMoisture1));

            textView = findViewById(R.id.textViewSoilMoistureDepth1);
            textView.setText(lastMeasurement.soilMoistureDepth1);

            textView = findViewById(R.id.textViewSoilMoisture2);
            textView.setText(String.valueOf(lastMeasurement.soilMoisture2));

            textView = findViewById(R.id.textViewSoilMoistureDepth2);
            textView.setText(lastMeasurement.soilMoistureDepth2);

            textView = findViewById(R.id.textViewSoilMoisture3);
            textView.setText(String.valueOf(lastMeasurement.soilMoisture3));

            textView = findViewById(R.id.textViewSoilMoistureDepth3);
            textView.setText(lastMeasurement.soilMoistureDepth3);

            textView = findViewById(R.id.textViewBatteryVoltage);
            textView.setText(String.valueOf(lastMeasurement.batteryVoltage));
        }
        else
        {
            try
            {
                textView = findViewById(R.id.textViewTimestamp);
                textView.setText(R.string.could_not_update);
                textView.setBackgroundColor(getResources().getColor(R.color.red));
            }
            catch(Exception ex)
            {
                // This exception is reached after after multiple settings and main screen invoke in quick succession
                // textView = findViewById(R.id.textViewTimestamp); is in that case null
                /*
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(getApplicationContext(), "exception", duration);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                */
            }
        }
    }

    /** onCreate
     * Register and set up everything which is needed for application run
     * navcontroler with menu, swiperefresh
     * */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        lastMeasurement = new LastMeasurement();
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);

        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        // Swipe refresh callback
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        swipeRefresh.setOnRefreshListener(() ->
                {
                    /*  This method performs refresh operation after pull update.
                        setRefreshing(false) is called in processFinish().
                    */
                    // Fetch data from url from property
                    FetchData fetchData = new FetchData();
                    fetchData.delegate = MainActivity.this;
                    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    String url = preference.getString("URL", "Not set");

                    //result will be process in processFinish()
                    if(url == "Not set")
                    {
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_set_url), duration);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        swipeRefresh.setRefreshing(false);
                    }
                    else
                    {
                        fetchData.execute(url);
                    }
                }
                );
    }

    /** onResume
     * perform refresh onResume meteo
     * */
    @Override
    protected void onResume() {
        super.onResume();

        // Fetch data from url from property
        FetchData fetchData = new FetchData();
        fetchData.delegate = MainActivity.this;
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String url = preference.getString("URL", "Not set");
        swipeRefresh.setRefreshing(true);
        if(url == "Not set")
        {
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_set_url), duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            swipeRefresh.setRefreshing(false);
        }
        else
        {
            fetchData.execute(url);
        }
    }

    /** onCreateOptionsMenu
     * Inflate the menu (add items to the action bar menu from resource)
     * */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /** onOptionsItemSelected
     * Handle action bar item clicks automatically depends on a parent
     * specification in AndroidManifest.xml
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        // Start Settings activity
        if (id == R.id.action_settings)
        {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /** onSupportNavigateUp
     * Handle action bar Up(back) button
     * */
    @Override
    public boolean onSupportNavigateUp()
    {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}