package xyz.danielcortes.controllers.editorial;

import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import xyz.danielcortes.models.Editorial;
import xyz.danielcortes.repository.EditorialRepository;
import xyz.danielcortes.views.editorial.EditorialDeletePanel;

public class EditorialDeleteController {
  private EditorialDeletePanel view;
  private EditorialRepository editorialRepository;

  public EditorialDeleteController(EditorialDeletePanel view) {
    this.view = view;
    this.editorialRepository = new EditorialRepository();

    this.setupListeners();
    this.loadEditorialCombo();
  }

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

  private void delete(){
    Editorial selected = (Editorial) this.view.getEditorialCombo().getSelectedItem();
    if(!validateEditorial(selected)) return;

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

  private boolean validateEditorial(Editorial editorial){
    if (editorial== null) {
      JOptionPane.showMessageDialog(
          this.view.getContentPane(),
          "No hay editorial seleccionada",
          "Error",
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    return true;
  }

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

  private void loadEditorialCombo(){
    List<Editorial> editoriales = this.editorialRepository.getAll();
    JComboBox<Editorial> comboBox = this.view.getEditorialCombo();
    comboBox.removeAllItems();
    for(Editorial editorial: editoriales){
      comboBox.addItem(editorial);
    }
  }

  public EditorialDeletePanel getView() {
    return view;
  }
}
