package cn.iselab.mooctest.user.configure;

import cn.iselab.mooctest.user.model.Integral;
import cn.iselab.mooctest.user.service.IntegralService;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author ROKG
 * @Description
 * @Date: Created in 下午9:18 2018/5/23
 * @Modified By:
 */
@Data
@Component
public class IntegralMap implements ApplicationContextAware{

    public ConcurrentHashMap<String,Integral> map=new ConcurrentHashMap<>();

    @Autowired
    IntegralService integralService;

    @Override
    public void setApplicationContext(ApplicationContext ac){
        integralService= ac.getBean(IntegralService.class);
        List<Integral> integrals=integralService.findIntegrals();
        integrals.forEach(integral -> {
            if (!map.containsKey(integral.getSource())){
                map.put(integral.getSource(),integral);
            }
        });
    }

    public Integral get(String event){
        if (map.containsKey(event)) {
            return map.get(event);
        }else {
            return null;
        }
    }

    public Map<String,Integral> reload(){
        map.clear();
        List<Integral> integrals=integralService.findIntegrals();
        integrals.forEach(integral -> {
            if (!map.containsKey(integral.getSource())){
                map.put(integral.getSource(),integral);
            }
        });
        return map;
    }
}
