package org.takiguchi.cerberus.cerberusapp.service.servicemanager;

import org.springframework.stereotype.Component;
import org.takiguchi.cerberus.cerberusapp.exception.InternalServerErrorException;
import org.takiguchi.cerberus.cerberusapp.model.Application;

import java.util.List;

@Component
public class ServiceManagerProvider {
    private final List<ServiceManager> serviceManagers;

    public ServiceManagerProvider(List<ServiceManager> serviceManagers) {
        this.serviceManagers = serviceManagers;
    }

    public ServiceManager getServiceManager(Application application) {
        ServiceManager result;
        switch (application.getServiceType()) {
            case FAKE:
                result = getServiceByClass(FakeServiceManager.class);
                break;
            case SERVICE:
                result = getServiceByClass(LinuxServiceManager.class);
                break;
            case DOCKER:
                result = getServiceByClass(DockerServiceManager.class);
                break;
            default:
                throw new InternalServerErrorException("");
        }

        return result;
    }

    private ServiceManager getServiceByClass(Class<? extends ServiceManager> serviceManagerClass) {
        return serviceManagers.stream()
                .filter(serviceManagerClass::isInstance)
                .findFirst()
                .orElseThrow(InternalServerErrorException::new);
    }
}
