package com.axis.innovators.box.decompilation.gui;

import org.benf.cfr.reader.api.OutputSinkFactory;
import org.benf.cfr.reader.api.SinkReturns.Decompiled;
import org.benf.cfr.reader.api.SinkReturns.ExceptionMessage;
import org.benf.cfr.reader.api.SinkReturns;

import javax.swing.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class CFROutputSinkFactory implements OutputSinkFactory {
    private JTextArea codeArea;
    private StringBuilder output = new StringBuilder();

    public CFROutputSinkFactory(JTextArea codeArea) {
        this.codeArea = codeArea;
    }

    public CFROutputSinkFactory() {
    }

    @Override
    public List<SinkClass> getSupportedSinks(SinkType sgetOutputinkType, Collection<SinkClass> collection) {
        return Collections.singletonList(SinkClass.DECOMPILED);
    }


    public String getOutput() {
        return output.toString();
    }

    @Override
    public <T> Sink<T> getSink(SinkType sinkType, SinkClass sinkClass) {
        if (sinkClass == SinkClass.DECOMPILED) {
            return (Sink<T>) new Sink<SinkReturns.Decompiled>() {
                @Override
                public void write(Decompiled decompiled) {
                    if (codeArea != null) {
                        SwingUtilities.invokeLater(() ->
                                codeArea.setText(decompiled.getJava())
                        );
                    }
                    output.append(decompiled.getJava()).append("\n");
                }
            };
        }
        return null;
    }
}
