package xyz.danielcortes.controllers.autor;

import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import xyz.danielcortes.models.Autor;
import xyz.danielcortes.repository.AutorRepository;
import xyz.danielcortes.views.autor.AutorDeletePanel;

public class AutorDeleteController {
  private AutorDeletePanel view;
  private AutorRepository autorRepository;

  public AutorDeleteController(AutorDeletePanel view){
    this.view = view;
    this.autorRepository = new AutorRepository();
    this.setupListeners();
    this.loadAutorCombo();
  }

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

  private void delete() {
    Autor selected = (Autor) this.view.getAutorCombo().getSelectedItem();
    if(!validateAutor(selected)) return;

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

  private boolean validateAutor(Autor autor) {
    if (autor == null) {
      JOptionPane.showMessageDialog(
          this.view.getContentPane(),
          "No hay autor seleccionado",
          "Error",
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    return true;
  }

  public void reload(){
    loadAutorCombo();
  }

  private void loadAutorCombo(){
    List<Autor> autores = this.autorRepository.getAll();
    JComboBox<Autor> combobox = this.view.getAutorCombo();
    combobox.removeAllItems();
    for(Autor autor: autores) {
      combobox.addItem(autor);
    }
  }

  public AutorDeletePanel getView() {
    return view;
  }

}
