package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.example.demo.dto.TaskDto;
import com.example.demo.dto.UserDto;
import com.example.demo.enums.TaskStatusEnum;
import com.example.demo.models.ProjectPO;
import com.example.demo.models.TaskPO;
import com.example.demo.models.UserPO;
import com.example.demo.repository.TaskRepository;

@Service
public class TaskService {
	
	private final TaskRepository taskRepository;
	
	public TaskService(TaskRepository taskRepository) {
		this.taskRepository = taskRepository;
	}
	
	/**
	 * Update a specific task
	 * @param id The id of the task
	 * @param taskDto The updated task
	 * @return
	 */
	public void updateTask(Integer id, TaskDto taskDto) {
		Optional<TaskPO> taskPO = taskRepository.findById(id);
		taskPO.get().setDescription(taskDto.getDescription());
		taskPO.get().setStatus(taskDto.getStatus());
		taskPO.get().setTitle(taskDto.getTitle());
		taskPO.get().setUsers(this.convertUserDtoTOUserPO(taskDto.getUsers()));
		this.taskRepository.save(taskPO.get());
	}
	
	/**
	 * 
	 * @param id
	 */
	public void deleteTask(Integer id) {
		taskRepository.deleteById(id);
	}
	
	public TaskPO createTask(TaskPO task) {
		task.setStatus(TaskStatusEnum.OPEN);
		return taskRepository.save(task);
	}
	
	public List<TaskPO> loadProjectTasks(ProjectPO projectPO) {
		return taskRepository.findByProject(projectPO);
	}
	
	/**
	 * Convert a UserDto object into a UserPO object
	 * @param userListDto The UserDto objects
	 * @return The UserPO objects
	 */
	private List<UserPO> convertUserDtoTOUserPO(List<UserDto> userListDto) {
		List<UserPO> userListPO = new ArrayList<>();
		
		userListDto.stream().forEach(userDto -> {
			UserPO userPO = new UserPO();
			userPO.setFirstName(userDto.getFirstName());
			userPO.setId(userDto.getId());
			userPO.setLastName(userDto.getLastName());
			
			userListPO.add(userPO);
		});
		
		return userListPO;
	}

}
