package com.csnf.service;

import com.csnf.entity.Product;
import com.csnf.mapper.ProductMapper;
import com.csnf.util.Conditional;
import com.csnf.util.PageUtil;
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 ProductService implements IProductService {
    private ProductMapper productMapper;

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

    @Override
    public void addProduct(Product product) {
        productMapper.insert(product);
    }

    @Override
    public Product getProductDetailsById(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        return product;
    }

    @Override
    public void updateProduct(Product product) {
        productMapper.updateByPrimaryKey(product);
    }

    @Override
    public void deleteProduct(Integer productId) {
        productMapper.deleteByPrimaryKey(productId);
    }

    @Override
    public List<Product> getAllProduct(PageUtil pageUtil) {
        List<Product> productList = productMapper.selectByConditional(null, null, null, null, null, pageUtil);
        return productList;
    }

    @Override
    public List<Product> getProductByConditional(Conditional conditional, PageUtil pageUtil) {
        List<Product> productList = productMapper.selectByConditional(conditional.getProductName(), conditional.getCategoryId(), conditional.getIsEnabled(), conditional.getMinPrice(), conditional.getMaxPrice(), pageUtil);
        return productList;
    }
}
