package cn.ftebox.service.impl;

import cn.ftebox.entity.BlogType;
import cn.ftebox.entity.Blogger;
import cn.ftebox.entity.Link;
import cn.ftebox.service.BlogTypeService;
import cn.ftebox.service.BloggerService;
import cn.ftebox.service.LinkService;
import cn.ftebox.util.Const;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

@Component
public class InitComponent implements ServletContextListener, ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        InitComponent.applicationContext = applicationContext;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        // 博客类别
        BlogTypeService blogTypeService = (BlogTypeService) applicationContext.getBean("blogTypeService");
        List<BlogType> blogTypeList = blogTypeService.countList();
        application.setAttribute(Const.BLOG_TYPE_COUNT_LIST, blogTypeList);

        // 博主信息
        BloggerService bloggerService = (BloggerService) applicationContext.getBean("bloggerService");
        Blogger blogger = bloggerService.find();
        blogger.setPassword(null);
        application.setAttribute(Const.BLOGGER, blogger);

        // 友情链接
        LinkService linkService = (LinkService) applicationContext.getBean("linkService");
        List<Link> linkList = linkService.list(null);
        application.setAttribute(Const.LINK_LIST, linkList);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}
