/*
 * Copyright (C) 2026  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.ui.dialog;

import org.aglais.zms.i18n.InterpolatingResourceBundle;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.ResourceBundle;

/**
 * A custom file chooser implementation extending {@link JFileChooser}
 * <p>
 * When showing a save dialog it checks if the file already exists and asks the user about overwriting it.
 */
public class FileChooser extends JFileChooser {

    @Override
    public int showSaveDialog(Component parent) throws HeadlessException {
        InterpolatingResourceBundle uiComponent = (InterpolatingResourceBundle) ResourceBundle.getBundle("ui_component");
        boolean retry;
        int result;

        do {
            retry = false;
            result = super.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                File file = getSelectedFile();

                if (file.exists()) {
                    if (JOptionPane.showOptionDialog(parent,
                            uiComponent.getString("overwrite_file", file.getName()),
                            uiComponent.getString("dialog_overwrite_file_title"),
                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                            new String[]{uiComponent.getString("overwrite"), uiComponent.getString("cancel")},
                            uiComponent.getString("cancel")) != JOptionPane.OK_OPTION) {
                        retry = true;
                    }
                }
            }
        } while (retry);

        return result;
    }
}
