package com.atlassian.stash.internal.plugin;

import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.PluginController;
import com.hazelcast.spring.context.SpringAware;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.Serializable;

@SpringAware
public class PluginControllerOperation implements Runnable, Serializable {

    private final String key;
    private final PluginOperationType type;

    private transient volatile ClusteredPluginPersistentStateStore store;
    private transient volatile PluginAccessor accessor;
    private transient volatile PluginController controller;

    public PluginControllerOperation(String key, PluginOperationType type) {
        this.key = key;
        this.type = type;
    }

    @Override
    public void run() {
        try (ClusteredPluginPersistentStateStore.ReadOnlyMarker state = store.markReadOnly()) {
            type.apply(accessor, controller, key);
        }
    }

    @Autowired
    public void setClusteredPluginPersistentStateStore(ClusteredPluginPersistentStateStore store) {
        this.store = store;
    }

    @Autowired
    public void setPluginAccessor(PluginAccessor accessor) {
        this.accessor = accessor;
    }

    @Resource(name = "pluginManager") // we need to inject the delegate, so that we don't get into an infinite loop
    public void setPluginController(PluginController controller) {
        this.controller = controller;
    }

}
