package ajax;

import java.util.*;
import java.sql.*;
import java.io.*;
import java.net.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

public class getVid{

public String slurp (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}




public InputStream get(String urlstring){

HttpURLConnection conn = null;

try{


URL url = new URL (urlstring);
conn = (HttpURLConnection)url.openConnection();	
conn.setRequestProperty("User-agent","Mozilla/4.0");

return (conn.getInputStream());


}
catch(Exception e)
{
System.err.println(e);
return null;
}


}



public String getHitVideo(String band){

try{
band = band.replaceAll(" ","+");
String urlstring = "http://ws.audioscrobbler.com/1.0/artist/"+band+"/toptracks.xml";
System.out.println(urlstring);
InputStream toptrackslist = (get(urlstring));

Document d = new SAXBuilder().build(toptrackslist); 
String hitSong = (d.getRootElement().getChild("track").getChild("name").getText());

hitSong = hitSong.replaceAll(" ","+");
hitSong = URLEncoder.encode(hitSong);

urlstring = ("http://gdata.youtube.com/feeds/videos?alt=rss&vq="+band+"+"+hitSong);

System.out.println(urlstring);
InputStream videolist = ((get(urlstring)));

d = new SAXBuilder().build(videolist); 

String hitVideoName = (d.getRootElement().getChild("channel").getChild("item").getChild("title").getText());
String hitVideoLink = (d.getRootElement().getChild("channel").getChild("item").getChild("link").getText());
String hitVideoID   =  hitVideoLink.substring(31);

// <object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/y84gW_5ZFKE&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/y84gW_5ZFKE&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object>
String hitVideoEmbed = "<object width=\"425\" height=\"355\"><param name=\"movie\" value=\"http://www.youtube.com/v/"+hitVideoID+"&rel=1\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/"+hitVideoID+"&rel=1\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"355\"></embed></object>";

return (("<div class=\"bbg3\">"+hitVideoName+"</div>\n")+(hitVideoEmbed));
}
catch(Exception e)
{return "";
}


  }
}