package com.sf.sdk.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;

public abstract class BaseActivity extends AppCompatActivity {

    protected Activity activity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.activity = this;
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_common);
        initActionBar();
        ViewGroup content = findViewById(R.id.activity_content);
        getLayoutInflater().inflate(getLayoutResId(), content, true);
        initSafeInsets();
        initViews();
    }

    protected abstract int getLayoutResId();

    protected abstract void initViews();

    protected boolean showHomeUp() {
        return true;
    }

    protected void initActionBar() {
        setSupportActionBar(findViewById(R.id.toolbar));
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            boolean showHomeUp = showHomeUp();
            actionBar.setDisplayHomeAsUpEnabled(showHomeUp);
            actionBar.setDisplayShowTitleEnabled(true);
        }
        Window window = getWindow();
        WindowCompat.setDecorFitsSystemWindows(window, false);
        WindowInsetsControllerCompat windowInsetsController = new WindowInsetsControllerCompat(window, window.getDecorView());
        windowInsetsController.setAppearanceLightStatusBars(false);
    }

    private void initSafeInsets() {
        View topBar = findViewById(R.id.top_bar);
        View content = findViewById(android.R.id.content);
        ViewCompat.setOnApplyWindowInsetsListener(content, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            topBar.setPadding(0, systemBars.top, 0, 0);
            content.setPadding(0, 0, 0, systemBars.bottom);
            return insets;
        });
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
