package com.sharefaith.thesharefaithapp.base;

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

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.ui.SFBibleActivity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by sfwebsitedev on 3/10/16.
 */
public class SFBibleDownloader
{
    SFApplication mApplication = SFApplication.getInstance();
    String filePath;
    boolean unzip;
    boolean refresh;

    public SFBibleDownloader()
    {

    }

    public String downloadBible( String address )
    {
        //Log.d( "mTag","hit downloadBible" );
        unzip = true;
        refresh = false;
        filePath = mApplication.getFilesDir() +"/"+ mApplication.getString( R.string.sf_bibles_path )+mApplication.getSfCurrentBible().mAbreviation+ ".tar.bz2";
        BibleDownload bibleDownload = new BibleDownload();
        bibleDownload.execute( address );
        SFUtil.logSiteEvent( "Download Bible version");
        mApplication.logEvent( "app_action","bible_download" );
        return null;
    }

    public String downloadChapter( String address,int bookIndex, int chapter)
    {
        unzip = false;
        filePath = mApplication.getFilesDir() +"/"+ mApplication.getString( R.string.sf_bibles_path )+
                mApplication.getSfCurrentBible().mAbreviation + "/" + mApplication.getBook( bookIndex ).mAbbreviation;
        checkPath();
        filePath = filePath + "/" + Integer.toString( chapter ) + ".html";
        SFAppData appData = new SFAppData();
        appData.addPathToBibleAccessHistory( mApplication.getSfCurrentBible().mAbreviation + "/" +
                mApplication.getBook( bookIndex ).mAbbreviation + "/" + Integer.toString( chapter ) + ".html");
        BibleDownload bibleDownload = new BibleDownload();
        bibleDownload.execute( address );
        mApplication.logEvent( "app_action","bible_chapter" );
        return null;
    }

    private void checkPath()
    {
        File file = new File( filePath );
        if(!file.exists())
        {
            file.mkdirs();
        }
    }

    private class BibleDownload extends AsyncTask<String, String, String>
    {
        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
    /*@Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }*/

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground( String... f_url )
        {
            //Log.d( "mTag","hit doInBackgroun with url " + f_url[0] );
            int count;
            try
            {
                URL url = new URL( f_url[0] );
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                //int lenghtOfFile = conection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream( url.openStream() );

                // Output stream
                OutputStream output = new FileOutputStream( filePath );

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read( data )) != -1)
                {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    //publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write( data, 0, count );
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();
                SFAppData appData = new SFAppData();
                //appData.setDataForVersionDownload();

            } catch (Exception e)
            {
                Log.e( "Error: ", e.getMessage() );
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
    /*protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
            }*/

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
                // dismiss the dialog after the file was downloaded
            if(unzip)
            {
                SFBibleActivity.unzipBible();
            }
        }
    }
}
