package de.nl.moo.data.loader.systems;

import de.nl.moo.data.beans.systems.SystemsApplyerBean;
import de.nl.moo.data.beans.systems.SystemsBean;
import de.nl.moo.data.beans.systems.SystemsSystemBean;
import de.nl.moo.data.dao.GameBeanDAO;
import de.nl.moo.data.loader.AbstractBeanLoader;
import org.springframework.beans.factory.annotation.Autowired;

import javax.inject.Provider;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class SystemsBeanLoader extends AbstractBeanLoader<SystemsBean> {

    @Autowired
    private SystemsBean systemsBean = null;
    @Autowired
    private Provider<SystemsSystemBeanLoader> systemLoaderProvider = null;
    @Autowired
    private Provider<SystemsApplyerBeanLoader> applyerLoaderProvider = null;

    public SystemsBeanLoader() {
        super();
    }

    @Override
    protected SystemsBean load(GameBeanDAO dao) {

        List<SystemsApplyerBean> applyers = this.loadApplyers(dao);
        this.systemsBean.setApplyers(applyers);

        List<SystemsSystemBean> systems = this.loadSystems(dao);
        this.systemsBean.setSystems(systems);

        return this.systemsBean;
    }

    // ##############################################

    private List<SystemsApplyerBean> loadApplyers(GameBeanDAO dao) {
        Path file = dao.getFile();
        Path parent = file.getParent();

        List<String> paths = dao.getList("applyers");
        List<SystemsApplyerBean> applyers = new ArrayList<>();
        paths.stream()
                .map(parent::resolve)
                .map(this::loadApplyer)
                .forEach(applyers::add);

        return applyers;
    }

    private SystemsApplyerBean loadApplyer(Path path) {
        SystemsApplyerBeanLoader beanLoader = this.applyerLoaderProvider.get();
        SystemsApplyerBean applyerBean = beanLoader.load(path);
        return applyerBean;
    }

    // ##############################################

    private List<SystemsSystemBean> loadSystems(GameBeanDAO dao) {
        Path file = dao.getFile();
        Path parent = file.getParent();

        List<String> paths = dao.getList("systems");
        List<SystemsSystemBean> systems = new ArrayList<>();
        paths.stream()
                .map(parent::resolve)
                .map(this::loadSystem)
                .forEach(systems::add);

        return systems;
    }

    private SystemsSystemBean loadSystem(Path path) {
        SystemsSystemBeanLoader beanLoader = this.systemLoaderProvider.get();
        SystemsSystemBean systemBean = beanLoader.load(path);
        return systemBean;
    }
}
