package com.lemonhc.mplus.classes;

/**
 * Created by kangsh on 2017. 2. 1..
 * <p>
 * tif 파일을 다운로드 받아서 이미지뷰에 보여주게 하는 클래스
 * 오픈소스를 이용하였음 (https://github.com/Kernelzero/Android-TiffBitmapFactory.git)
 */

import android.app.DownloadManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import org.beyka.tiffbitmapfactory.TiffBitmapFactory;

import java.io.File;
import java.io.IOException;

/**
 * AsyncTask for Download image from URL.
 * @String Parameter of execute( ), doInBackground( ) method.
 * @Void Parameter of onProgressUpdate( ) method.
 * @Bitmap Return value of doInBackground( ) method, and Parameter of onPostExecute( ) method.
 */
public class DownloadTask extends AsyncTask<String, Void, Bitmap> {

    private static final String TAG = "DownloadTask";

    // Downloaded bitmap image will be set on this ImageView.
    private final ImageView mImageView;

    Context mContext;

    /** Constructor		Get ImageView from activity. */
    public DownloadTask(ImageView iv, Context context) {
        mImageView = iv;
        this.mContext = context;
    }


    /** Works before doInBackground( ) */
    @Override
    protected void onPreExecute() {
        Log.i(TAG, "[onPreExecute( )  ] Do nothing.");

        super.onPreExecute();
    }

    /** Works should be done in here. */
    @Override
    protected Bitmap doInBackground(String... url) {
        Log.i(TAG, "[doInBackground( )] Download Image from:");

        Bitmap bitmap = null;

        try {
            bitmap = downloadUrl(url[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    /** Works after doInBackground( ) */
    @Override
    protected void onPostExecute(Bitmap result) {
        Log.i(TAG, "[onPostExecute( ) ] Set downloaded image on ImageView.(0x" + Integer.toHexString(mImageView.getId()) + ")");

        if (result != null) {
            super.onPostExecute(result);

            mImageView.setImageBitmap(result);
            mImageView.invalidate();
        } else {
            Log.i(TAG, "[onPostExecute( ) ] Image downloading failed !!!!!!!!!!!!!!!!!!! ");
        }
    }


    // Image downloading method.
    private Bitmap downloadUrl(String imageUrl) throws IOException {
        Log.i(TAG, "                " + imageUrl);

//        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        Bitmap bitmap = null;
        try {

            File direct = new File("/EMR2");

            if (!direct.exists()) {
                direct.mkdirs();
            }

            // file path 정리

            Log.i("1", direct.getAbsolutePath()); // /EMR2
            Log.i("2", Environment.getExternalStorageDirectory().getAbsolutePath()); // /storage/emulated/0
            Log.i("3", this.mContext.getApplicationInfo().dataDir); // /data/data/com.dbs.mplus.kunkuk
            Log.i("4", this.mContext.getApplicationInfo().sourceDir); // /data/app/com.dbs.mplus.kunkuk-1/base.apk
            Log.i("5", this.mContext.getApplicationInfo().publicSourceDir); // /data/app/com.dbs.mplus.kunkuk-1/base.apk
            Log.i("6", Environment.DIRECTORY_DOWNLOADS); // Download


            DownloadManager mgr = (DownloadManager) this.mContext.getSystemService(Context.DOWNLOAD_SERVICE);

            Uri downloadUri = Uri.parse(imageUrl);
            DownloadManager.Request request = new DownloadManager.Request(
                    downloadUri);

            request.setAllowedNetworkTypes(
                    DownloadManager.Request.NETWORK_WIFI
                            | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle("EMR 영상 다운로드")
                    .setDescription("파일을 다운로드 중입니다....")
                    .setDestinationInExternalPublicDir(direct.getAbsolutePath(), "test.tif");
//                    .setDestinationInExternalPublicDir("AAAA" , "TEST.tif" );

            //mgr.enqueue(request);


            Log.i("absolutPath -->>", this.mContext.getApplicationInfo().sourceDir + direct.getAbsolutePath());

            File file = new File("/storage/emulated/0/EMR2/" + "test.tif");
//            FileUtils.copyURLToFile(url, file);
            Log.i("file path : ", file.getAbsolutePath());

//            request.setDestinationInExternalPublicDir( "/APP_NAME/", FileNameGetter.getFileName(DATA..url) );

            TiffBitmapFactory.Options options = new TiffBitmapFactory.Options();
            options.inJustDecodeBounds = false;
//            options.inAvailableMemory = 1024 * 1024 * 10; //10 mb
//            bitmap = TiffBitmapFactory.decodeFile(file, options);

            int dirCount = options.outDirectoryCount;

            bitmap = TiffBitmapFactory.decodeFile(file, options);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }
}
