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

package com.elex_project.examples.components.progress;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ProgressMonitorExample extends JPanel {

	public ProgressMonitorExample() {
		super();
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

		final JButton button = new JButton("Start");



		this.add(button);

		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				Task task = new Task();
				task.execute();
			}
		});
	}

	public class Task extends SwingWorker<Integer, Integer> {
		private final ProgressMonitor progressMonitor;
		Task(){
			super();
			progressMonitor = new ProgressMonitor(ProgressMonitorExample.this,
					"Progress Monitor", "Running a long task..", 0, 100);
		}
		@Override
		protected Integer doInBackground() throws Exception {
			int i = 0;
			while (i < 100) {
				if(progressMonitor.isCanceled()){
					this.cancel(true);
					break;
				}

				Thread.sleep(100);
				i++;

				progressMonitor.setProgress(i);
				publish(i);
			}
			return i;
		}

		@Override
		protected void done() {
			if (!progressMonitor.isCanceled()) {
				System.out.println("Job done.");
				progressMonitor.setProgress(100);
				progressMonitor.setNote("Done!");
			} else {
				System.out.println("User canceled.");
			}

			progressMonitor.close();
		}
	}

	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 ProgressMonitorExample());

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


	}
}
