package com.csnf.service;

import com.csnf.entity.Category;
import com.csnf.mapper.CategoryMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class CategoryService implements ICategoryService {
    private CategoryMapper categoryMapper;

    public CategoryService() {
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSession session = builder.build(in).openSession();
            categoryMapper = session.getMapper(CategoryMapper.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addCategory(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public Category getCategoryById(Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        return category;
    }

    @Override
    public void updateCategory(Category category) {
        categoryMapper.updateByPrimaryKey(category);
    }

    @Override
    public void deleteCategory(Integer categoryId) {
        categoryMapper.deleteByPrimaryKey(categoryId);
    }

    @Override
    public List<Category> getAllCategory() {
        List<Category> list = categoryMapper.selectAll();
        return list;
    }
}
