package org.keyscience.BackgroundTask;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/***
 * REPLACEMENT FOR HttpDrawableAsync -- Courtesy of stackoverflow!
 */

public class URLImageParser implements Html.ImageGetter {
    Context c;
    TextView container;

    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(TextView t, Context c) {
        this.c = c;
        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            if ( result != null ) {
                // set the correct bound according to the result from HTTP call
                Log.d("height", "" + result.getIntrinsicHeight());
                Log.d("width", "" + result.getIntrinsicWidth());

                DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

                int dwidth = (metrics.widthPixels * 90) / 100;

                int dheight = result.getIntrinsicHeight() * dwidth
                        / result.getIntrinsicWidth();

                int totalGapW = dwidth - result.getIntrinsicHeight() - 200/*My Text view Padding*/;
                int totalGapH = dheight - result.getIntrinsicWidth() - 200/*My Text view Padding*/;

                urlDrawable.setBounds(0, 0, dwidth, dheight);
                result.setBounds(0, 0, dwidth, dheight);

                // change the reference of the current drawable to the result
                // from the HTTP call
                urlDrawable.drawable = result;

                // redraw the image by invalidating the container
                URLImageParser.this.container.invalidate();

                // For ICS
                URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
                        + dheight));

                URLImageParser.this.container.setWidth((URLImageParser.this.container.getWidth()
                        + dwidth));

                URLImageParser.this.container.setText(container.getText());

                // Pre ICS
                URLImageParser.this.container.setEllipsize(null);

                //    URLImageParser.this.container.setGravity(Gravity.CENTER);
            }
        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
                        + drawable.getIntrinsicHeight());
                return drawable;
            } catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {

            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream stream = urlConnection.getInputStream();

            return stream;

        }
    }
}