package xyz.danielcortes.controllers.libro;

import java.util.List;
import javax.swing.JComboBox;
import xyz.danielcortes.models.Libro;
import xyz.danielcortes.repository.LibroRepository;
import xyz.danielcortes.views.libro.LibroDeletePanel;

public class LibroDeleteController {

  private LibroDeletePanel view;
  private LibroValidator validator;
  private LibroRepository libroRepository;

  public LibroDeleteController(LibroDeletePanel view) {
    this.view = view;
    this.libroRepository = new LibroRepository();
    this.validator = new LibroValidator(this.libroRepository);
    this.loadLibroCombo();
    this.setupListeners();
  }

  private void setupListeners() {
    this.view.getEliminarButton().addActionListener(e -> this.delete());
  }

  private void delete() {
    Libro selected = (Libro) this.view.getLibroCombo().getSelectedItem();
    if(!validator.validateLibro(selected)) return;

    this.libroRepository.delete(selected);
    this.reload();
  }

  public void reload() {
    this.loadLibroCombo();
  }

  private void loadLibroCombo() {
    List<Libro> libros = this.libroRepository.getAll();
    JComboBox<Libro> combobox = this.view.getLibroCombo();
    combobox.removeAllItems();
    for(Libro libro: libros){
      combobox.addItem(libro);
    }
  }

  public LibroDeletePanel getView() {
    return view;
  }
}
