/*
 * Decompiled with CFR 0.152.
 */
package org.jivesoftware.smack.util;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.jivesoftware.smack.util.WriterListener;

public class ObservableWriter
extends Writer {
    Writer wrappedWriter = null;
    List<WriterListener> listeners = new ArrayList<WriterListener>();

    public ObservableWriter(Writer wrappedWriter) {
        this.wrappedWriter = wrappedWriter;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        this.wrappedWriter.write(cbuf, off, len);
        String str = new String(cbuf, off, len);
        this.notifyListeners(str);
    }

    @Override
    public void flush() throws IOException {
        this.wrappedWriter.flush();
    }

    @Override
    public void close() throws IOException {
        this.wrappedWriter.close();
    }

    @Override
    public void write(int c) throws IOException {
        this.wrappedWriter.write(c);
    }

    @Override
    public void write(char[] cbuf) throws IOException {
        this.wrappedWriter.write(cbuf);
        String str = new String(cbuf);
        this.notifyListeners(str);
    }

    @Override
    public void write(String str) throws IOException {
        this.wrappedWriter.write(str);
        this.notifyListeners(str);
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        this.wrappedWriter.write(str, off, len);
        str = str.substring(off, off + len);
        this.notifyListeners(str);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void notifyListeners(String str) {
        WriterListener[] writerListeners = null;
        List<WriterListener> list = this.listeners;
        synchronized (list) {
            writerListeners = new WriterListener[this.listeners.size()];
            this.listeners.toArray(writerListeners);
        }
        for (int i = 0; i < writerListeners.length; ++i) {
            writerListeners[i].write(str);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void addWriterListener(WriterListener writerListener) {
        if (writerListener == null) {
            return;
        }
        List<WriterListener> list = this.listeners;
        synchronized (list) {
            if (!this.listeners.contains(writerListener)) {
                this.listeners.add(writerListener);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void removeWriterListener(WriterListener writerListener) {
        List<WriterListener> list = this.listeners;
        synchronized (list) {
            this.listeners.remove(writerListener);
        }
    }
}
