package com.radiopirate.android.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

/**
 * Get the Title of a stream using the Shoutcast Metadata Protocol From:
 * http://uniqueculture.net/2010/11/stream-metadata-plain-java/
 */
public class IcyStreamMeta {

    private static final String TAG = "RP - IcyStreamMeta";
    private URL streamUrl;
    private Map<String, String> metadata;
    private boolean isError;

    public IcyStreamMeta(URL streamUrl) {
        setStreamUrl(streamUrl);

        isError = false;
    }

    public URL getStreamUrl() {
        return streamUrl;
    }

    /**
     * Get stream title
     * 
     * @return String
     * @throws IOException
     */
    public String getStreamTitle() throws IOException {
        Map<String, String> data = getMetadata();

        if (data == null) {
            return "";
        }

        if (!data.containsKey("StreamTitle"))
            return "";

        return data.get("StreamTitle").trim();
    }

    /**
     * Get artist using stream's title
     * 
     * @return String
     * @throws IOException
     */
    public String getArtist() throws IOException, StringIndexOutOfBoundsException  {
        Map<String, String> data = getMetadata();
        if (data == null || !data.containsKey("StreamTitle"))
        {
            return "";
        }
        String streamTitle = data.get("StreamTitle");
        String title = streamTitle.substring(0, streamTitle.indexOf("-"));
        return title.trim();
    }

    /**
     * Get title using stream's title
     * 
     * @return String
     * @throws IOException
     */
    public String getTitle() throws IOException, StringIndexOutOfBoundsException {
        Map<String, String> data = getMetadata();

        if (data == null || !data.containsKey("StreamTitle"))
        {
            return "";
        }

        String streamTitle = data.get("StreamTitle");
        String artist = streamTitle.substring(streamTitle.indexOf("-") + 1);
        return artist.trim();
    }

    public void refreshMeta() throws IOException {
        retreiveMetadata();
    }

    private Map<String, String> getMetadata() throws IOException {
        if (metadata == null) {
            refreshMeta();
        }

        return metadata;
    }

    private void retreiveMetadata() throws IOException {
        URLConnection con = streamUrl.openConnection();
        con.setRequestProperty("Icy-MetaData", "1");
        con.setRequestProperty("Connection", "close");
        con.connect();

        int metaDataOffset = 0;
        Map<String, List<String>> headers = con.getHeaderFields();
        InputStream stream = con.getInputStream();

        if (headers.containsKey("icy-metaint")) {
            // Headers are sent via HTTP
            metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
        }
        // else: There would be a way to get it from the stream content, but it is inefficient, and unneeded for our
        // streams

        // In case no data was sent
        if (metaDataOffset == 0) {
            isError = true;
            Log.e(TAG, "retreiveMetadata - no offset");
            return;
        }

        // Read metadata
        int b;
        int count = 0;
        int metaDataLength = 4080; // 4080 is the max length
        boolean inData = false;
        StringBuilder metaData = new StringBuilder();
        // Stream position should be either at the beginning or right after headers
        while ((b = stream.read()) != -1) {
            count++;

            // Length of the metadata
            if (count == metaDataOffset + 1) {
                metaDataLength = b * 16;
            }

            if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
                inData = true;
            } else {
                inData = false;
            }
            if (inData) {
                if (b != 0) {
                    metaData.append((char) b);
                }
            }
            if (count > (metaDataOffset + metaDataLength)) {
                break;
            }

        }

        // Set the data
        metadata = IcyStreamMeta.parseMetadata(metaData.toString());

        // Close
        stream.close();
    }

    public boolean isError() {
        return isError;
    }

    private void setStreamUrl(URL streamUrl) {
        this.metadata = null;
        this.streamUrl = streamUrl;
        this.isError = false;
    }

    private static Map<String, String> parseMetadata(String metaString) {
        Map<String, String> metadata = new HashMap<String, String>();
        //metaString = "StreamTitle='Kid Kasino  I'm Evil'";
        Log.v("IcyStreamMeta", metaString);
        String[] metaParts = metaString.split(";");
        Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'(.*)\\'$"); //match pattern <characters>='<any>'
        Matcher m;
        for (int i = 0; i < metaParts.length; i++) {
            m = p.matcher(metaParts[i]);
            if (m.find()) {
            	String key = ((String) m.group(1)).trim();
            	String value = ((String) m.group(2)).trim();
                metadata.put(key, value);
            }
        }

        return metadata;
    }
}
@@ -4855,38 +4855,37 @@
 %0D%0A    %7D%0D%0A%0D%0A    p
-rivate
+ublic
  static Map%3CStri
@@ -4986,435 +4986,201 @@
 hMap
-%3CString, String%3E();%0D%0A        //metaString = %22StreamTitle='Kid Kasino  I'm Evil'%22;%0D%0A        Log.v(%22IcyStreamMeta%22, metaString);%0D%0A        String%5B%5D metaParts = metaString.split(%22;%22);%0D%0A        Pattern p = Pattern.compile(%22%5E(%5Ba-zA-Z%5D+)=%5C%5C'(.*)%5C%5C'$%22); //match pattern %3Ccharacters%3E='%3Cany%3E'%0D%0A        Matcher m;%0D%0A        for (int i = 0; i %3C metaParts.length; i++) %7B%0D%0A            m = p.matcher(metaParts%5Bi%5D);%0D%0A            if (m.find()) %7B
+();%0D%0A%0D%0A        String%5B%5D metaParts = metaString.split(%22;%22);%0D%0A        for (int i = 0; i %3C metaParts.length; i++) %7B%0D%0A            String part = metaParts%5Bi%5D.substring(0, metaParts%5Bi%5D.indexOf(%22=%22));
 %0D%0A  
@@ -5193,168 +5193,152 @@
     
-%09
 String 
-key = ((String) m.group(1)).trim();%0D%0A            %09String value = ((String) m.group(2)).trim();%0D%0A                metadata.put(key, value);%0D%0A            %7D
+songname = metaParts%5Bi%5D.substring(metaParts%5Bi%5D.indexOf(%22'%22)+1, metaParts%5Bi%5D.lastIndexOf(%22'%22));%0D%0A            metadata.put(part, songname);
 %0D%0A  
@@ -5382,8 +5382,10 @@
     %7D%0D%0A%7D
+%0D%0A

Fix issues with ' in metadata