/*
 * Copyright 2008 nori090
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.coderepos.nori090.pcraw;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class A {
    private static final Pattern p = Pattern.compile( "^index(_[a-z]+)?\\.txt$" );

    public static void main( String[] args ) {

        try {
            URL url = new URL( "http://extremeyp.ath.cx/index.txt" );
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream(), "UTF-8" ) );
            String s = null;
            String stream_url = null;
            while ( ( s = br.readLine() ) != null ) {
                String[] ss = s.split( "<>" );
                if ( ss.length == 19 ) {
                    if ( "RAW".equals( ss[9] ) && "".equals( ss[4] ) ) {
                        Matcher m = p.matcher( ss[0] );
                        if ( m.find() ) {
                            StringBuilder sb = new StringBuilder( "http://localhost:7144/stream/" );
                            sb.append( ss[1] );
                            sb.append( "?tip=" );
                            sb.append( ss[2] );
                            stream_url = sb.toString();
                            break;
                        }
                    }
                }
            }
            br.close();
            System.out.println( stream_url );
            PCRaw pcraw = new PCRaw( stream_url );
            for ( int i = 0; i < 10; i++ ) {
                Thread.sleep( 10000 );
                byte[] tmp = pcraw.getData();
                if ( tmp != null ) {
                    System.out.printf( "↓以下データです。%s", new String( tmp, "UTF-8" ) );
                }
            }
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
    }
}
