package com.openosrs.client.plugins;

import com.openosrs.client.api.AgentAPI;
import com.openosrs.client.core.ClientCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Consumer;

/**
 * Abstract base class for plugins.
 */
public abstract class AbstractPlugin implements Plugin {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    protected PluginContext context;
    protected volatile boolean enabled = false;
    
    @Override
    public final void onEnable(PluginContext context) {
        this.context = context;
        this.enabled = true;
        
        try {
            enable();
        } catch (Exception e) {
            this.enabled = false;
            throw e;
        }
    }
    
    @Override
    public final void onDisable() {
        this.enabled = false;
        
        try {
            disable();
        } finally {
            this.context = null;
        }
    }
    
    /**
     * Implement plugin enable logic here.
     */
    protected abstract void enable();
    
    /**
     * Implement plugin disable logic here.
     */
    protected abstract void disable();
    
    /**
     * Check if plugin is enabled.
     */
    protected boolean isEnabled() {
        return enabled;
    }
    
    /**
     * Get the agent API.
     */
    protected AgentAPI getAPI() {
        return context != null ? context.getAPI() : null;
    }
    
    /**
     * Get the client core.
     */
    protected ClientCore getClientCore() {
        return context != null ? context.getClientCore() : null;
    }
    
    /**
     * Register an event listener.
     */
    protected void addEventListener(String eventType, Consumer<Object> listener) {
        if (context != null) {
            context.getEventSystem().addEventListener(eventType, listener);
        }
    }
}