package ru.ulstu.project.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.repository.ProjectRepository;

import java.util.List;

import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class ProjectService {

    private final ProjectRepository projectRepository;
    private final DeadlineService deadlineService;

    public ProjectService(ProjectRepository projectRepository,
                          DeadlineService deadlineService) {
        this.projectRepository = projectRepository;
        this.deadlineService = deadlineService;
    }

    public List<Project> findAll() {
        return projectRepository.findAll();
    }

    @Transactional
    public Project create(ProjectDto projectDto) {
        Project newProject = copyFromDto(new Project(), projectDto);
        newProject = projectRepository.save(newProject);
        return newProject;
    }

    private Project copyFromDto(Project project, ProjectDto projectDto) {
        project.setTitle(projectDto.getTitle());
        project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
        return project;
    }

    public Project save(ProjectDto projectDto) {
        if (isEmpty(projectDto.getId())) {
            return create(projectDto);
        } else {
            return update(projectDto);
        }
    }

    private Project update(ProjectDto projectDto) {
        throw new RuntimeException("not implemented yet");
    }

    public Project findById(Integer id) {
        return projectRepository.findOne(id);
    }

}
