package com.amazon.ads.apidemo.fragments;

import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.amazon.ads.apidemo.MainActivity;
import com.amazon.ads.apidemo.api.RemoteApiClient;

/**
 * Base fragment class with common functionality for all fragments
 */
public abstract class BaseFragment extends Fragment {
    protected RemoteApiClient mApiClient;
    protected Handler mHandler;

    protected void initializeBase() {
        mApiClient = ((MainActivity) requireActivity()).getApiClient();
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Check if API client is connected
     */
    protected boolean checkConnection() {
        if (mApiClient == null || !mApiClient.isConnected()) {
            Toast.makeText(getContext(), "API not connected", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * Show error message to user
     */
    protected void showError(String title, String message) {
        Toast.makeText(getContext(), title + ": " + message, Toast.LENGTH_LONG).show();
        updateLastApiCall("Failed: " + message);
    }

    /**
     * Update last API call status in MainActivity
     */
    protected void updateLastApiCall(String message) {
        ((MainActivity) requireActivity()).updateLastApiCall(message);
    }

    /**
     * Show visual press effect on button
     */
    protected void showButtonPressEffect(Button button) {
        if (button != null) {
            button.setPressed(true);
            button.postDelayed(() -> button.setPressed(false), 100);
        }
    }
}
