package speiger.src.ui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;

import speiger.src.data.Registry;

public class DownloadTask extends JDialog {
	private static final long serialVersionUID = 142921231931795121L;
	
	public DownloadTask(JFrame owner) {
		super(owner, owner != null);
		setTitle("Downloading Images");
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 326, 153);
		setLocationRelativeTo(owner);
		getContentPane().setLayout(new BorderLayout());
		JPanel content = new JPanel(null);
		content.setBorder(new EmptyBorder(5, 5, 5, 5));
		
		JLabel label = new JLabel("Downloading location Images");
		label.setBounds(10, 11, 210, 14);
		content.add(label);
		
		JProgressBar progress = new JProgressBar();
		progress.setStringPainted(true);
		progress.setString("0 / 0");
		progress.setBounds(10, 38, 284, 25);
		content.add(progress);
		
		getContentPane().add(content, BorderLayout.CENTER);
		
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
		getContentPane().add(buttonPane, BorderLayout.SOUTH);
		AtomicBoolean task = new AtomicBoolean();
		
		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(T -> {
			task.set(true);
			dispose();
		});
		buttonPane.add(cancelButton);
		Thread.ofPlatform().start(() -> {
			Registry.INSTANCE.downloadMissingIcons(T -> {
				EventQueue.invokeLater(() -> {
					progress.setString(T[0]+" / "+T[1]);
					progress.setMaximum(T[1]);
					progress.setValue(T[0]);
					repaint();
				});
			}, task, () -> {
				EventQueue.invokeLater(this::dispose);
			});
		});
		setVisible(true);
	}
}
