/*
 * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which
 * is available at http://www.opensource.org/licenses/lgpl-2.1.php.
 *
 * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF
 * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT
 * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE.  IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR
 * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF
 * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC
 * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL
 * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE
 * FOREGOING.
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.remote;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.log4j.Logger;
import org.broad.igv.feature.GenomeDescriptor;
import org.broad.igv.feature.GenomeManager;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.IGVHttpUtils;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author jrobinso
 */
public class SequenceServletWrapper {

    /**
     * Field description
     */
    public static boolean SEQUENCE_SERVER_AVAILALBLE = true;
    public static final int CONNECTION_TIMEOUT = 20000;
    private static Logger logger = Logger.getLogger(SequenceServletWrapper.class);


    public static byte[] readBytes(String location, String chr, int start, int end) {

        byte[] bytes = new byte[end - start];

        if (!SEQUENCE_SERVER_AVAILALBLE) {
            return bytes;
        }




        try {

            URL url = new URL(location);
            URLConnection connection = IGVHttpUtils.openConnection(url);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setDoOutput(true);

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write("chr=" + chr);
            out.write("&start=" + start);
            out.write("&end=" + end);
            out.close();

            InputStream cis = connection.getInputStream();


            DataInputStream is =
                    new DataInputStream(new BufferedInputStream(cis));
            int offset = 0;
            int numRead = 0;
            while ((offset < bytes.length) && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            is.close();

            return bytes;


        } catch (IOException ex) {

            // Log connection errors once per session to prevent filling the log
            if (SEQUENCE_SERVER_AVAILALBLE) {
                SEQUENCE_SERVER_AVAILALBLE = false;

                showUnavailableMessage();

                logger.error("Error retrieving sequence from : " + location + ex.getMessage());
            }
            return null;
        }
    }

    private static void showUnavailableMessage() throws HeadlessException {
        MessageUtils.showMessage(
                "<html>The IGV server at the Broad Institute is currently unavailable.  " +
                        "Features that require a reference sequence, <br>" +
                        "such as displaying alignment mismatches, will be disabled.  " +
                        "If this problem persists please <br>" +
                        "send email to igv-help@broadinstitute.org");
    }


}
