package ch.ds1.challengeTask.TodoList.todolist;

import ch.ds1.challengeTask.TodoList.entry.Entry;
import ch.ds1.challengeTask.TodoList.entry.EntryRepository;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TodoListService {

  private final TodoListRepository todoListRepository;

  private final EntryRepository entryRepository;

  @Autowired
  public TodoListService(TodoListRepository todoListRepository, EntryRepository entryRepository) {
    this.todoListRepository = todoListRepository;
    this.entryRepository = entryRepository;
  }

  public List<TodoList> getTodoLists() {
    return todoListRepository.findAll();
  }

  public TodoList getTodoList(Long todoListId) {
    return todoListRepository.findById(todoListId).orElseThrow(
        () -> new IllegalStateException("TodoList with Id " + todoListId + " does not exist"));
  }

  public TodoList addNewTodoList(TodoList todoList) {
    todoList.setCreationDate(LocalDate.now());
    todoListRepository.save(todoList);
    return todoList;
  }

  public void deleteTodoList(Long todoListId) {
    boolean exists = todoListRepository.existsById(todoListId);
    if (!exists) {
      throw new IllegalStateException("TodoList with id " + todoListId + " does not exist");
    }
    todoListRepository.deleteById(todoListId);
  }

  @Transactional
  public TodoList updateTodoList(Long todoListId, String name) {
    TodoList todoList = todoListRepository.findById(todoListId)
        .orElseThrow(() -> new IllegalStateException(
            "TodoList with id " + todoListId + " does not exist"));

    if (name != null && name.length() > 0 && !Objects.equals(todoList.getName(), name)) {
      todoList.setName(name);
    }
    return todoList;
  }


  public List<Entry> getEntriesFromTodoList(Long todoListId) {
    TodoList todoList = todoListRepository.findById(todoListId).orElseThrow(
        () -> new IllegalStateException("TodoList with id " + todoListId + " does not exist"));
    return todoList.getEntries();
  }

  public Entry addNewEntryToTodoList(Long todoListId, Entry entry) {
    TodoList todoList = todoListRepository.findById(todoListId).orElseThrow(
        () -> new IllegalStateException("TodoList with id " + todoListId + " does not exist"));

    if (entry.getTitle() != null && entry.getTitle().length() > 0) {
      todoList.addEntry(entry);
      entryRepository.save(entry);
    } else {
      throw new IllegalStateException("Must set a title for new entry");
    }
    return entry;
  }
}
