/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.components.chooser;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileChooserExample extends JPanel {
	public FileChooserExample() {
		super(new BorderLayout());

		final JToolBar toolBar = new JToolBar();
		final JButton btnOpen = new JButton("Open");
		final JButton btnSave = new JButton("Save");
		toolBar.add(btnOpen);
		toolBar.add(btnSave);

		final JTextArea textArea = new JTextArea();

		// 레이아웃에 추가
		add(toolBar, BorderLayout.NORTH);
		add(new JScrollPane(textArea), BorderLayout.CENTER);

		final ActionListener actionListener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				final JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileFilter(new FileNameExtensionFilter("Text File", "txt"));
				if (btnOpen == actionEvent.getSource()) {
					int response = fileChooser.showOpenDialog(FileChooserExample.this);
					if (response==JFileChooser.APPROVE_OPTION){
						File file = fileChooser.getSelectedFile();
						try {
							String text = Files.readString(file.toPath());
							textArea.setText(text);
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}
				} else if (btnSave == actionEvent.getSource()) {
					fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					int response = fileChooser.showSaveDialog(FileChooserExample.this);
					if (response==JFileChooser.APPROVE_OPTION){
						File file = fileChooser.getSelectedFile();
						try {
							Files.writeString(new File(file, "test.txt").toPath(), textArea.getText());
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}
				}
			}
		};
		btnOpen.addActionListener(actionListener);
		btnSave.addActionListener(actionListener);

	}

	public static void main(String... args) {

		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new FileChooserExample());

		SwingUtilities.invokeLater(() -> {
			jFrame.setVisible(true);
		});


	}

	class DummyIcon implements Icon {

		@Override
		public void paintIcon(Component component, Graphics graphics, int x, int y) {
			graphics.setColor(Color.DARK_GRAY);
			graphics.fillRect(x, y, x + getIconWidth(), y + getIconHeight());
		}

		@Override
		public int getIconWidth() {
			return 16;
		}

		@Override
		public int getIconHeight() {
			return 16;
		}
	}
}
