import java.awt.Font;
import java.util.ArrayList;

/**
 * Piano class, with a main method for hands-on play using the keyboard.
 *   @author Dave Reed
 *   @version 9/8/13
 */
public class Piano {
    private ArrayList<PianoWire> wires;

    /**
     * Constructs a Piano object with wires starting at C.
     *   @param numWires the number of wires in the Piano
     */
    public Piano(int numWires) {
        this.wires = new ArrayList<PianoWire>();
        for (int i = 0; i < numWires; i++) {
            this.wires.add(new PianoWire(i));
        }
    }

    /**
     * Strikes the specified wire and sets it to vibrating.
     *   @param wireNum the wire number (offset from C)
     */
    public void strikeWire(int wireNum) {
        if (wireNum >= 0 && wireNum < this.wires.size()) {
            this.wires.get(wireNum).strike();
        }
    }

    /**
     * Plays the sounds corresponding to all of the struck wires.
     */
    public void play() {
        double combined = 0.0;
        for (int i = 0; i < this.wires.size(); i++) {
            combined += this.wires.get(i).sample();
        }
        StdAudio.play(combined);     
    }
    
    /////////////////////////////////////////////////////////////////
    
    public static void main(String[] args) {
        String keys = "w3e4rt6y7u8izsxdcvgbhnjm,";  
        StdDraw.setFont(new Font("Monospaced", Font.PLAIN, 16));
        StdDraw.textLeft(0.0, 1.00, "     PIANO KEY MAPPINGS");
        StdDraw.textLeft(0.0, 0.91, " 3 4   6 7 8   s d   g h j");
        StdDraw.textLeft(0.0, 0.88, "w e r t y u i z x c v b n m ,");
        StdDraw.textLeft(0.0, 0.83, "^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^");
        StdDraw.textLeft(0.0, 0.80, "C D E F G A B C D E F G A B C");
        
        Piano p = new Piano(keys.length());
        while (true) { 
            if (StdDraw.hasNextKeyTyped()) {
                p.strikeWire(keys.indexOf(StdDraw.nextKeyTyped()));
            }
            p.play();
        }
    }
}
