package org.broad.igv.util.stream;

import net.sf.samtools.seekablestream.SeekableStream;
import org.broad.tribble.util.URLHelper;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URL;

/**
 * TODO Get rid of this class
 * Temporary workaround to let us use IGVUrlHelper, think
 * it's what's causing the issue with reading TDF from web start over http
 */
public class IGVSeekableHTTPStream extends SeekableStream {

    private long position = 0;
    private long contentLength = -1;

    private URLHelper helper;

    public IGVSeekableHTTPStream(final URL url) {

        this.helper = new IGVUrlHelper(url);
        try {
            this.contentLength = this.helper.getContentLength();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    public long position() {
        return position;
    }

    public long length() {
        return contentLength;
    }

    @Override
    public long skip(long n) throws IOException {
        long bytesToSkip = Math.min(n, contentLength - position);
        position += bytesToSkip;
        return bytesToSkip;
    }

    public boolean eof() throws IOException {
        return contentLength > 0 && position >= contentLength;
    }

    public void seek(final long position) {
        this.position = position;
    }

    public int read(byte[] buffer, int offset, int len) throws IOException {

        if (offset < 0 || len < 0 || (offset + len) > buffer.length) {
            throw new IndexOutOfBoundsException("Offset="+offset+",len="+len+",buflen="+buffer.length);
        }
        if (len == 0) {
            return 0;
        }

        InputStream is = null;
        int n = 0;
        try {

            long endRange = position + len - 1;
            // IF we know the total content length, limit the end range to that.
            if (contentLength > 0) {
                endRange = Math.min(endRange, contentLength);
            }
            is = this.helper.openInputStreamForRange(position, endRange);

            while (n < len) {
                int count = is.read(buffer, offset + n, len - n);
                if (count < 0) {
                    if (n == 0) {
                        return -1;
                    } else {
                        break;
                    }
                }
                n += count;
            }

            position += n;

            return n;

        }

        catch (IOException e) {
            // THis is a bit of a hack, but its not clear how else to handle this.  If a byte range is specified
            // that goes past the end of the file the response code will be 416.  The MAC os translates this to
            // an IOException with the 416 code in the message.  Windows translates the error to an EOFException.
            //
            //  The BAM file iterator  uses the return value to detect end of file (specifically looks for n == 0).
            e.printStackTrace();
            if (e.getMessage().contains("416") || (e instanceof EOFException)) {
                if (n == 0) {
                    return -1;
                } else {
                    position += n;
                    // As we are at EOF, the contentLength and position are by definition =
                    contentLength = position;
                    return n;
                }
            } else {
                throw e;
            }

        }

        finally {
            if (is != null) {
                is.close();
            }
        }
    }


    public void close() throws IOException {
        // Nothing to do
    }


    public int read() throws IOException {
        byte []tmp=new byte[1];
        read(tmp,0,1);
        return (int) tmp[0] & 0xFF;
    }

    @Override
    public String getSource() {
        return this.helper.getUrl().toExternalForm();
    }
}

@@ -1,8 +1,557 @@
+/*%0A * Copyright (c) 2007-2013 The Broad Institute, Inc.%0A * SOFTWARE COPYRIGHT NOTICE%0A * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.%0A *%0A * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.%0A *%0A * This software is licensed under the terms of the GNU Lesser General Public License (LGPL),%0A * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.%0A */%0A%0A
 package 
@@ -628,24 +628,56 @@
 ableStream;%0A
+import org.apache.log4j.Logger;%0A
 import org.b
@@ -795,31 +795,8 @@
 am;%0A
-import java.net.Proxy;%0A
 impo
@@ -1041,24 +1041,96 @@
 leStream %7B%0A%0A
+    static Logger log = Logger.getLogger(IGVSeekableHTTPStream.class);%0A%0A
     private 
@@ -1313,16 +1313,72 @@
 r(url);%0A
+        log.debug(%22Getting content length for %22 + url);%0A
         
@@ -1554,16 +1554,32 @@
 ception(
+e.getMessage(), 
 e);%0A    
@@ -2190,24 +2190,190 @@
 xception %7B%0A%0A
+        String stats = %22Offset=%22+offset+%22,len=%22+len+%22,buflen=%22+buffer.length;%0A        log.debug(%22Reading from %22 + getSource());%0A        log.debug(%22Stats: %22 + stats);%0A
         if (
@@ -2483,61 +2483,13 @@
 ion(
-%22Offset=%22+offset+%22,len=%22+len+%22,buflen=%22+buffer.length
+stats
 );%0A 
@@ -2853,32 +2853,111 @@
 ;%0A            %7D%0A
+            log.debug(%22Trying to read range %22 + position + %22 to %22 + endRange);%0A
             is =
@@ -3379,24 +3379,105 @@
 ition += n;%0A
+            log.debug(%22Read %22 + n  + %22 bytes, current position now %22 + position);
 %0A           
@@ -4013,34 +4013,43 @@
         
-e.printStackTrace(
+log.error(e.getMessage(), e
 );%0A     

Add many log.debug statements for SU2C debugging