package ch.ds1.challengeTask.TodoList.entry;

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 EntryService {

  private final EntryRepository entryRepository;

  @Autowired
  public EntryService(EntryRepository entryRepository) {
    this.entryRepository = entryRepository;
  }

  public List<Entry> getEntries() {
    return entryRepository.findAll();
  }

  public Entry getEntry(Long entryId) {
    return entryRepository.findById(entryId).orElseThrow(
        () -> new IllegalStateException("Entry with id " + entryId + " does not exist"));
  }

  public void addNewEntry(Entry entry) {
    entry.setDone(false);
    entryRepository.save(entry);
  }

  public void deleteEntry(Long entryId) {
    boolean exists = entryRepository.existsById(entryId);
    if (!exists) {
      throw new IllegalStateException("Entry with id " + entryId + " does not exist");
    }
    entryRepository.deleteById(entryId);
  }


  @Transactional
  public Entry updateEntry(Long entryId, String title, boolean done) {
    Entry entry = entryRepository.findById(entryId).orElseThrow(
        () -> new IllegalStateException("Entry with id " + entryId + " does not exists"));

    if (title != null && title.length() > 0 && !Objects.equals(entry.getTitle(), title)) {
      entry.setTitle(title);
    }

    if (entry.isDone() != done) {
      entry.setDone(done);
    }
    return entry;
  }
}
