package com.openosrs.client.scripting;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

/**
 * Abstract base class for scripts with common functionality.
 */
public abstract class AbstractScript implements Script {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    public final void execute(ScriptContext context) throws Exception {
        context.setStatus(ScriptStatus.RUNNING);
        
        try {
            run(context);
            context.setStatus(ScriptStatus.COMPLETED);
        } catch (InterruptedException e) {
            context.setStatus(ScriptStatus.STOPPED);
            throw e;
        } catch (Exception e) {
            context.setStatus(ScriptStatus.FAILED);
            throw e;
        }
    }
    
    /**
     * Implement script logic here.
     */
    protected abstract void run(ScriptContext context) throws Exception;
    
    /**
     * Sleep with interruption check.
     */
    protected void sleep(long millis) throws InterruptedException {
        Thread.sleep(millis);
    }
    
    /**
     * Wait for a condition to be true.
     */
    protected boolean waitFor(Supplier<Boolean> condition, long timeoutMs) throws InterruptedException {
        long start = System.currentTimeMillis();
        
        while (System.currentTimeMillis() - start < timeoutMs) {
            if (condition.get()) {
                return true;
            }
            Thread.sleep(100);
        }
        
        return false;
    }
}