package danielcortes.xyz.views.dialogs;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class XLSFileChooser {

  private JFileChooser chooser;

  public XLSFileChooser(String suggestedName) {
    this.chooser = new JFileChooser();
    this.chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    this.chooser.setSelectedFile(new File(suggestedName + ".xls"));
    this.chooser.setFileFilter(new FileNameExtensionFilter("Excel 2007", "xls"));
  }

  public Path execute() {
    boolean accepted = this.chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION;
    if (accepted) {
      Path path = processFilePath(this.chooser.getSelectedFile().getPath());
      return path;
    } else {
      return null;
    }
  }

  private Path processFilePath(String pathString) {
    Path path;

    if (!pathString.endsWith(".xls")) {
      pathString = pathString + ".xls";
    }

    try {
      path = Paths.get(pathString);
    } catch (InvalidPathException e) {
      e.printStackTrace();

      JOptionPane.showMessageDialog(
          null,
          "El nombre de archivo entregado es invalido",
          "Error!",
          JOptionPane.ERROR_MESSAGE
      );
      return null;
    }

    try {
      Files.createFile(path);
    } catch (FileAlreadyExistsException e) {
      int response = JOptionPane.showConfirmDialog(
          null,
          "El archivo ya existe" + "\n" + "¿Desea sobreescribirlo?",
          "Confirmacion",
          JOptionPane.YES_NO_OPTION,
          JOptionPane.WARNING_MESSAGE
      );

      if (response != 0) {
        return null;
      }

    } catch (IOException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "No a sido posible crear el archivo",
          "Error!",
          JOptionPane.ERROR_MESSAGE
      );

      return null;
    }

    return path;
  }
}
