package Action;

import IHM.WorkingImage;
import Window.Interface;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ActionPerformFilter extends AbstractAction {

    Class p;

    public ActionPerformFilter(Class p) {
        super(p.getCanonicalName().substring(p.getCanonicalName().lastIndexOf('.') + 1, p.getCanonicalName().length()));
        this.p = p;
        if (WorkingImage.getInstance().getImages().size() == 0)
            setEnabled(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Thread thread = new Thread(new ThreadFilter());
        thread.start();
        Interface.getInstance().showWindow();
    }

    private class ThreadFilter implements Runnable {

        @Override
        public void run() {
            Interface.getInstance().remove(WorkingImage.getInstance());
            try {
                Method method = p.getDeclaredMethod("perform", BufferedImage.class);
                Object o = p.newInstance();
                BufferedImage tmp = (BufferedImage) method.invoke(o, WorkingImage.getInstance().getImage());
                WorkingImage.getInstance().setImage(tmp);
                Interface.getInstance().showWindow();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            }
        }
    }
}