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/10/16
 */
public class Piano {
    private ArrayList<PianoWire> wires;

    /**
     * Constructs a Piano object with wires starting at middle 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 middle 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 = "sedrfgyhujikl";  
        StdDraw.setFont(new Font("Monospaced", Font.PLAIN, 16));
        StdDraw.textLeft(0.00, 1.00, "PIANO KEY MAPPINGS");
        StdDraw.textLeft(0.02, 0.91, " e r   y u i   ");
        StdDraw.textLeft(0.02, 0.88, "s d f g h j k l");
        StdDraw.textLeft(0.02, 0.83, "^ ^ ^ ^ ^ ^ ^ ^");
        StdDraw.textLeft(0.02, 0.80, "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();
        }
    }
}
