package cn.feast.coding.service.generator;

import cn.feast.coding.mapper.generator.DataSourceMapper;
import cn.feast.coding.model.generator.Colunm;
import cn.feast.coding.model.generator.DataSource;
import cn.feast.coding.model.generator.Page;
import cn.feast.coding.tools.DataBaseTools;
import cn.feast.coding.tools.SysContants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created By FeastCoding.
 */
@Service
public class DataSourceService {

    @Autowired
    private DataSourceMapper mapper;

    public Integer save(DataSource dataSource) {
        return mapper.save(dataSource);
    }

    public void update(DataSource dataSource) {
        mapper.update(dataSource);
    }

    public void deleteById(Integer id) {
        mapper.deleteById(id);
    }

    public int queryByCount(DataSource dataSource) {
        return mapper.queryByCount(dataSource);
    }

    public List<DataSource> queryByList(Page page, DataSource dataSource) {
        String pageQueryCondition = " limit " + page.getStart() + " , " + page.getMaxRows();
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("name", dataSource.getName());
        paramsMap.put("jdbcUrl", dataSource.getJdbcUrl());
        paramsMap.put("jdbcUser", dataSource.getJdbcUser());
        paramsMap.put("jdbcPass", dataSource.getJdbcPass());
        paramsMap.put("isDefault", dataSource.getIsDefault());
        paramsMap.put("pageQueryCondition", pageQueryCondition);
        return mapper.queryByList(paramsMap);
    }

    public List<DataSource> queryByDataSource(DataSource dataSource) {
        return mapper.queryByDataSource(dataSource);
    }

    public DataSource queryById(Integer id) {
        return mapper.queryById(id);
    }

    public List<DataSource> queryAll() {
        return mapper.queryAll();
    }

    public boolean testConnection(DataSource dataSource) {
        int data = DataBaseTools.testConnection(dataSource);
        if (data == 0) {
            return false;
        } else {
            return true;
        }
    }

    public PageInfo<DataSource> queryPage(DataSource dataSource, int pageNum, int pageSize) {
        if (pageSize < 1)
            pageSize = SysContants.MAX_PAGE_ROWS;
        PageHelper.startPage(pageNum, pageSize);
        List<DataSource> list = mapper.queryByDataSource(dataSource);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
