package jp.ac.do_johodai.j314.sw.jc;

import javax.swing.*;
import java.io.*;
import java.awt.Color;
import java.awt.event.*;

public class JTextFieldInputStream extends InputStream implements ActionListener {
    JTextField textField;
    MyBuffer myBuffer;

    public JTextFieldInputStream(JTextField tf) {
        textField = tf;
        tf.addActionListener(this);
        myBuffer = new MyBuffer(tf);
    }

    public int read() throws IOException {
        try {
            return myBuffer.read();
        } catch (Exception e) {
            throw new IOException();
        }
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == textField) {
            myBuffer.addLine(textField.getText());
            textField.setText("");
        }
    }

    class MyBuffer {
        byte currentString[] = null;

        int counter = -1;

        boolean someOneWaiting = false;

        JTextField textField;

        MyBuffer(JTextField tf) {
            textField = tf;
            textField.setBackground(Color.white);
        }

        synchronized void addLine(String s) {
            if (someOneWaiting == false)
                return;
            if (currentString != null)
                return;
            currentString = (s + "\n").getBytes();
            counter = 0;
            notifyAll();
        }

        synchronized int read() throws Exception {
            while (currentString == null) {
                someOneWaiting = true;
                textField.setBackground(java.awt.Color.red);
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (counter >= currentString.length) {
                currentString = null;
                someOneWaiting = false;
                textField.setBackground(Color.white);
                counter = -1;
                return -1;
            }
            int retValue = currentString[counter];
            counter++;
            return retValue;
        }
    }
}
