package com.saptneel.themeselector;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SwitchCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.saptneel.themeselector.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Getting system default theme.
        int theme = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;

        /*Creating a shared preferences variable to save the user theme,
         which by default is set same as system default.*/
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isNight = sharedPreferences
                .getBoolean("NightMode", theme == Configuration.UI_MODE_NIGHT_YES);

        //Applying the theme mode.
        if(isNight) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        else AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        /*Applying the style saved by the user, which by default is also same as android default.
        This part is needed to be added to each activity if your app has more than 1.*/
        int styleId = sharedPreferences.getInt("Style", R.style.Theme_ThemeSelector);
        setTheme(styleId);

        //You need to apply the above code in your Main Activity. The code below can be changed.

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        super.onCreate(savedInstanceState);
        setContentView(binding.getRoot());

        binding.refresh.setOnRefreshListener(() -> {
            binding.refresh.setRefreshing(false);
            MainActivity.this.recreate();
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getTitle().equals("Styles and Theme")) {
            startActivity(new Intent(MainActivity.this, StylesAndTheme.class));
        }
        return super.onOptionsItemSelected(item);
    }

}