001package net.filebot.postprocess;
002
003import java.io.File;
004import java.util.stream.Stream;
005
006import groovy.lang.Closure;
007
008import net.filebot.format.ExpressionBindings;
009import net.filebot.format.MediaBindingBean;
010
011public class ApplyClosure implements ApplyStep {
012
013        private final Closure<?> closure;
014
015        public ApplyClosure(Closure<?> closure) {
016                this.closure = closure;
017        }
018
019        @Override
020        public boolean accept(File file, Object object) {
021                return true;
022        }
023
024        @Override
025        public void apply(File source, File destination, Object object, Feedback log) {
026                log.trace("Run Closure", destination);
027
028                // source, destination, object
029                Object[] args = Stream.of(source, destination, object).limit(closure.getMaximumNumberOfParameters()).toArray();
030
031                // make standard format bindings available in the closure
032                closure.setDelegate(new ExpressionBindings(new MediaBindingBean(object, destination)) {
033                        @Override
034                        protected boolean isUndefined(Object value) {
035                                // pass through binding values (even if null or empty) and never throw an exception as that would break the resolve strategy
036                                return false;
037                        }
038                });
039
040                // call with suitable number or arguments
041                Object result = closure.call(args);
042
043                log.trace(result, destination);
044        }
045
046        @Override
047        public String toString() {
048                return "CLOSURE";
049        }
050
051}