package kr.co.hanwha.hifive.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import kr.co.hanwha.hifive.R;

public class HFDownloadNewVersion {
    private Context mContext;
    private ProgressDialog mProgress;

    private String mFilename;
    private final String AUTHORITY = "kr.co.hanwha.hifive.fileprovider";
    private final String DATA_TYPE = "application/vnd.android.package-archive";

    private OnDownloadCallback onDownloadCallback;

    public HFDownloadNewVersion(@NonNull Context context, @NonNull String url, @NonNull OnDownloadCallback onDownloadCallback) {
        mContext = context;
        mFilename = mContext.getString(R.string.app_name) + "_" + "update.apk";
        this.onDownloadCallback = onDownloadCallback;

        doDownload(url);
    }

    private void doDownload(String url) {
        new DownloadNewVersion().execute(url);
    }

    private void doUpdate(String location) {
        String path = location + mFilename;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkURI;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            apkURI = FileProvider.getUriForFile(mContext, AUTHORITY, new File(path));
        } else {
            apkURI = Uri.fromFile(new File(path));
        }
        intent.setDataAndType(apkURI, DATA_TYPE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        mContext.startActivity(intent);
        onDownloadCallback.onApplicationNeedFinish();
    }

    class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgress = new ProgressDialog(mContext);
            mProgress.setCancelable(false);

            mProgress.setMessage("Downloading...");

            mProgress.setIndeterminate(true);
            mProgress.setCanceledOnTouchOutside(false);
            mProgress.show();

        }

        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            mProgress.setIndeterminate(false);
            mProgress.setMax(100);
            mProgress.setProgress(progress[0]);
            String msg = "";
            if (progress[0] > 99) {
                msg = "Finishing... ";
            } else {
                msg = "Downloading... " + progress[0] + "%";
            }
            mProgress.setMessage(msg);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            mProgress.dismiss();

            if (result) {
                Toast.makeText(mContext, "Update Done", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "Error: Try Again", Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        protected Boolean doInBackground(String... arg0) {
            Boolean flag = false;

            try {
                URL url = new URL(arg0[0]);

                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoInput(true);
                connection.connect();

                String PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Quest/";//String PATH = Environment.getExternalStorageDirectory() + "/Download/Quest/";
                File file = new File(PATH);
                file.mkdirs();

                File outputFile = new File(file, mFilename);

                if (outputFile.exists()) {
                    outputFile.delete();
                }

                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = connection.getInputStream();

                int total_size = 4000000;//size of apk

                byte[] buffer = new byte[1024];
                int len1 = 0;
                int per = 0;
                int downloaded = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                    downloaded += len1;
                    per = (int) (downloaded * 100 / total_size);
                    publishProgress(per);
                }
                fos.close();
                is.close();

                doUpdate(PATH);

                flag = true;
            } catch (Exception e) {
                Log.e("DOWNLOAD", "Update Error: " + e.getMessage());
                flag = false;
            }
            return flag;
        }
    }

    public interface OnDownloadCallback {
        void onApplicationNeedFinish();
    }
}
