package org.adaptlab.chpir.android.survey.Tasks;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync;
import org.adaptlab.chpir.android.activerecordcloudsync.NetworkNotificationUtils;
import org.adaptlab.chpir.android.survey.AppUtil;
import org.adaptlab.chpir.android.survey.R;
import org.adaptlab.chpir.android.survey.Models.Image;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class DownloadImagesTask extends AsyncTask<Void, Void, Void> {
    public static String ACCESS_TOKEN;
    private String IMAGE_URL_END_POINT;
    private final static String TAG = "ImageDownloader";

	private Context mContext;
	
	public DownloadImagesTask(Context context) {
		mContext = context;
	}

	@Override
	protected Void doInBackground(Void... arg0) {
		if (NetworkNotificationUtils.checkForNetworkErrors(mContext)) {
			downloadImages();
		}
		return null;
	}
	
	public void downloadImages() {
    	ACCESS_TOKEN = mContext.getResources().getString(R.string.backend_api_key);
    	ActiveRecordCloudSync.setAccessToken(ACCESS_TOKEN);
        ActiveRecordCloudSync.setVersionCode(AppUtil.getVersionCode(mContext));
        String[] endPointArray = ActiveRecordCloudSync.getEndPoint().split("/api/");
        IMAGE_URL_END_POINT = endPointArray[0];
        
        for (Image img : Image.getAll()) {
        	String url = IMAGE_URL_END_POINT + img.getPhotoUrl() + ActiveRecordCloudSync.getParams();
        	String filename = UUID.randomUUID().toString() + ".jpg";
			FileOutputStream filewriter = null;
        	try {
        		byte[] imageBytes = getUrlBytes(url);
        		filewriter = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
        		filewriter.write(imageBytes);
        		img.setBitmapPath(filename);
        		img.save();
        		Log.i(TAG, "image saved in " + filename);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (filewriter != null)
						filewriter.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
        }
    }
    
    private byte[] getUrlBytes(String urlSpec) throws IOException {
        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();
            
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return null;
            }
            
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.close();
            return out.toByteArray();
        } finally {
            connection.disconnect();
        }
    }

}

@@ -761,48 +761,8 @@
 EN;%0A
-    private String IMAGE_URL_END_POINT;%0A
     
@@ -1347,281 +1347,277 @@
     
-String%5B%5D endPointArray = ActiveRecordCloudSync.getEndPoint().split(%22/api/%22);%0A        IMAGE_URL_END_POINT = endPointArray%5B0%5D;%0A        %0A        for (Image img : Image.getAll()) %7B%0A        %09String url = IMAGE_URL_END_POINT + img.getPhotoUrl() + ActiveRecordCloudSync.getParams(
+%0A        for (Image img : Image.getAll()) %7B%0A        %09String%5B%5D imageUrl = img.getPhotoUrl().split(%22/%22);%0A        %09String url = ActiveRecordCloudSync.getEndPoint() + %22images/%22 + imageUrl%5B2%5D + %22/%22 + ActiveRecordCloudSync.getParams();%0A        %09Log.i(TAG, %22Image url: %22 + url
 );%0A 

use api to fetch images from server