package cn.edu.whu.boot.allocation.services.impl;

import cn.edu.whu.boot.allocation.entities.TaskCell;
import cn.edu.whu.boot.allocation.mapper.TaskCellMapper;
import cn.edu.whu.boot.allocation.services.TaskCellService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class TaskCellServiceImpl implements TaskCellService {

    private final TaskCellMapper taskCellMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public TaskCellServiceImpl(TaskCellMapper taskCellMapper) {
        this.taskCellMapper = taskCellMapper;
    }

    @Override
    public List<TaskCell> findByTaskId(int taskId) {
        return taskCellMapper.findByTaskId(taskId);
    }

    @Override
    public List<String> findGeojsonByTaskIdAndUserId(int taskId, int userId) {
        return taskCellMapper.findGeojsonByTaskIdAndUserId(taskId, userId);
    }

    @Override
    public Optional<String> findGeojsonByTaskIdAndGeohash(int taskId, String geohash) {
        return Optional.ofNullable(taskCellMapper.findGeojsonByTaskIdAndGeohash(taskId, geohash));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertList(List<TaskCell> list) {
        if (list != null && !list.isEmpty()) {
            taskCellMapper.insertForeach(list);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTaskId(int taskId) {
        taskCellMapper.deleteByTaskId(taskId);
    }

    @Override
    public Map<String, Object> getCoordinateRange(Integer taskId)
    {
        return taskCellMapper.getCoordinateRange(taskId);
    }
}
