
package mars.mobile;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.File;

import static mars.mobile.Received_listviewActivity.htmlSpannable;

class ImageLoadTask extends AsyncTask <Void, Object, Void>{

    DisplayMetrics metrics = new DisplayMetrics();
    private Context mContext;
    boolean img_is_exist =  false;
    Resources resources;
    //TwAjax t;

    public static final String DATA_DIR = Environment.getExternalStorageDirectory().getPath();
    public static final String IMG_CACHE_DIR = DATA_DIR + "/cache/imgs";


    /*
    public ImageLoadTask(Context context){
        mContext = context;
    }
*/
    public ImageLoadTask(Context context, SpannableStringBuilder htmlSpannable, TextView result) {
        mContext=context;
        // we need this to properly scale the images later
        //c.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        resources = context.getResources();
        metrics = resources.getDisplayMetrics();
        ///t= new TwAjax(context, true, false);
        initDataDirs();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // iterate over all images found in the html
        for (ImageSpan img : htmlSpannable.getSpans(0,
                htmlSpannable.length(), ImageSpan.class)) {

            Log.d("bb", "Loading: "+img.getSource());

            File cachedFile = getImageFile(img);
            if (!cachedFile.isFile()) {
             ///   t.urlDownloadToFile(img.getSource(), cachedFile.getAbsolutePath(), null);
                Log.d("bb", "Download done"+Environment.getExternalStorageDirectory().getPath());
            }
            if (cachedFile.isFile()) {
                Drawable d = new BitmapDrawable( mContext.getResources(), cachedFile.getAbsolutePath());

                // we use publishProgress to run some code on the
                // UI thread to actually show the image
                // -> onProgressUpdate()
                publishProgress(img, d);
            }

        }
        return null;
    }

    @Override
    protected void onPreExecute() {
            // we need this to properly scale the images later
            ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);

    }


    @Override
    protected void onProgressUpdate(Object[] values) {

        ImageSpan img = (ImageSpan) values[0];
        Drawable d = (Drawable) values[1];
        File cache = getImageFile(img);

        if (cache.isFile()) {

            Log.d("bb", "File OK");

            int width, height;
            int originalWidthScaled = (int) (d.getIntrinsicWidth() * metrics.density);
            int originalHeightScaled = (int) (d.getIntrinsicHeight() * metrics.density);
            if (originalWidthScaled > metrics.widthPixels) {
                height = d.getIntrinsicHeight() * metrics.widthPixels
                        / d.getIntrinsicWidth();
                width = metrics.widthPixels;
            } else {
                height = originalHeightScaled;
                width = originalWidthScaled;
            }

            d.setBounds(0, 0, width, height);

            // now we create a new ImageSpan
            ImageSpan newImg = new ImageSpan(d, img.getSource());

            // find the position of the old ImageSpan
            int start = htmlSpannable.getSpanStart(img);
            int end = htmlSpannable.getSpanEnd(img);

            // remove the old ImageSpan
            htmlSpannable.removeSpan(img);

            // add the new ImageSpan
            htmlSpannable.setSpan(newImg, start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


            Received_listviewActivity.result.setText(htmlSpannable);
        }
    }

    private File getImageFile(ImageSpan img) {


        return new File(IMG_CACHE_DIR + "/url_" + ImageLoadTask.cleanFilename(img.getSource()));
    }

    public static String cleanFilename(String url) {
        return url.replaceAll("[^a-z0-9.-]", "_");

    }

    public static void initDataDirs() {
        new File(DATA_DIR).mkdirs();
        new File(IMG_CACHE_DIR).mkdirs();

    }

}