package org.stepic.droid.receivers;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.squareup.otto.Bus;

import org.stepic.droid.base.MainApplication;
import org.stepic.droid.events.video.VideoCachedOnDiskEvent;
import org.stepic.droid.model.CachedVideo;
import org.stepic.droid.model.DownloadEntity;
import org.stepic.droid.model.Lesson;
import org.stepic.droid.model.Step;
import org.stepic.droid.preferences.UserPreferences;
import org.stepic.droid.store.ICancelSniffer;
import org.stepic.droid.store.IStoreStateManager;
import org.stepic.droid.store.operations.DatabaseFacade;
import org.stepic.droid.util.RWLocks;

import java.io.File;
import java.util.concurrent.ExecutorService;

import javax.inject.Inject;

public class DownloadCompleteReceiver extends BroadcastReceiver {

    @Inject
    UserPreferences mUserPrefs;
    @Inject
    DatabaseFacade mDatabaseFacade;
    @Inject
    IStoreStateManager mStoreStateManager;
    @Inject
    Bus bus;

    @Inject
    ICancelSniffer mCancelSniffer;

    @Inject
    ExecutorService mThreadSingleThreadExecutor;

    public DownloadCompleteReceiver() {
        MainApplication.component().inject(this);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        final long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

        mThreadSingleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                blockForInBackground(referenceId);
                Log.d("thread", Thread.currentThread().getName()+ " ");
            }
        });
    }

    private void blockForInBackground(final long referenceId) {
        try {
            RWLocks.DownloadLock.writeLock().lock();

            DownloadEntity downloadEntity = mDatabaseFacade.getDownloadEntityIfExist(referenceId);
            if (downloadEntity != null) {
                long video_id = downloadEntity.getVideoId();
                final long step_id = downloadEntity.getStepId();
                mDatabaseFacade.deleteDownloadEntityByDownloadId(referenceId);


                File downloadFolderAndFile = new File(mUserPrefs.getUserDownloadFolder(), video_id + "");
                String path = Uri.fromFile(downloadFolderAndFile).getPath();

                if (mCancelSniffer.isStepIdCanceled(step_id)) {
                    File file = new File(path);
                    if (file.exists()) {
                        file.delete();
                    }
                    mCancelSniffer.removeStepIdCancel(step_id);
                }
                else
                {
                    //is not canceled
                    final CachedVideo cachedVideo = new CachedVideo(step_id, video_id, path, downloadEntity.getThumbnail());
                    cachedVideo.setQuality(downloadEntity.getQuality());
                    mDatabaseFacade.addVideo(cachedVideo);

                    final Step step = mDatabaseFacade.getStepById(step_id);
                    step.set_cached(true);
                    step.set_loading(false);
                    mDatabaseFacade.updateOnlyCachedLoadingStep(step);
                    mStoreStateManager.updateUnitLessonState(step.getLesson());
                    final Lesson lesson = mDatabaseFacade.getLessonById(step.getLesson());
                    Handler mainHandler = new Handler(MainApplication.getAppContext().getMainLooper());
                    //Say to ui that ui is cached now
                    Runnable myRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (lesson != null)
                                bus.post(new VideoCachedOnDiskEvent(step_id, lesson, cachedVideo));
                        }
                    };
                    mainHandler.post(myRunnable);
                }
            }
        } finally {
            RWLocks.DownloadLock.writeLock().unlock();
        }
    }

}
@@ -549,16 +549,52 @@
 l.Step;%0A
+import org.stepic.droid.model.Unit;%0A
 import o
@@ -638,16 +638,16 @@
 rences;%0A
-
 import o
@@ -1771,16 +1771,17 @@
 etName()
+ 
 + %22 %22);%0A
@@ -2775,46 +2775,959 @@
     
-%7D%0A                else%0A               
+    Step step = mDatabaseFacade.getStepById(step_id);%0A                    if (step != null) %7B%0A                        Lesson lesson = mDatabaseFacade.getLessonById(step.getLesson());%0A                        if (lesson != null) %7B%0A                            Unit unit = mDatabaseFacade.getUnitByLessonId(lesson.getId());%0A                            if (unit != null && mCancelSniffer.isUnitIdIsCanceled(unit.getId())) %7B%0A                                mStoreStateManager.updateUnitLessonAfterDeleting(lesson.getId());//automatically update section%0A                                mCancelSniffer.removeUnitIdCancel(unit.getId());%0A                                if (mCancelSniffer.isSectionIdIsCanceled(unit.getSection())) %7B%0A                                    mCancelSniffer.removeSectionIdCancel(unit.getSection());%0A                                %7D%0A                            %7D%0A%0A                        %7D%0A                    %7D%0A                %7D else
  %7B%0A 
@@ -4993,32 +4993,32 @@
 %7D%0A            %7D%0A
-
         %7D finall
@@ -5018,16 +5018,25 @@
  finally
+%0A%0A       
  %7B%0A     

add state updater to receiver