package tourplaner.ui;

import javafx.scene.image.Image;
import tourplaner.business.ConfigHelper;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ProgressBar {
    private int status;
    private JFrame frame;
    private JProgressBar progressBar;

    public ProgressBar(String title){
        this.frame = new JFrame(title);
        File pathToFile = new File(ConfigHelper.getIniString(ConfigHelper.getStandartConfig(), "start", "logo"));
        try {
            BufferedImage image = ImageIO.read(pathToFile);
            this.frame.setIconImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        Container content = this.frame.getContentPane();
        this.progressBar = new JProgressBar();
        this.progressBar.setValue(0);
        this.progressBar.setStringPainted(true);
        TitledBorder border = BorderFactory.createTitledBorder("Laden....");
        this.progressBar.setBorder(border);
        content.add(this.progressBar, BorderLayout.NORTH);
        this.frame.setSize(300, 100);
        this.frame.setVisible(true);
    }

    public void addProgress(int add){
        this.status += add;
        this.progressBar.setValue(this.status);
        closeOnFinish();
    }

    private void closeOnFinish(){
        if(this.status >= 100){
            closeProgress();
        }
    }

    public void setProgress(int set){
        this.status = set;
        closeOnFinish();
    }

    public void closeProgress(){
        this.frame.setVisible(false);
    }

    public int getProgressSize(int todo, int maxLevel){
        int steps = (progressBar.getValue() - maxLevel) / todo;
        if(steps < 0) steps = steps*-1;
        return steps;
    }
}
