package info.puzz.a10000sentences;

import com.activeandroid.query.Select;

import java.security.SecureRandom;
import java.util.List;
import java.util.Random;

import info.puzz.a10000sentences.dao.Dao;
import info.puzz.a10000sentences.models.Sentence;
import info.puzz.a10000sentences.models.SentenceCollection;
import info.puzz.a10000sentences.models.SentenceHistory;
import info.puzz.a10000sentences.models.SentenceStatus;

public final class SentenceCollectionsService {

    private static final Random RANDOM = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes());

    public static Sentence nextSentence(SentenceCollection collection, String exceptSentenceId) {
        Dao.reloadCollectionCounter(collection);

        int status = SentenceStatus.TODO.getStatus();
        if (RANDOM.nextInt(Constants.MAX_REPEAT_SENTENCES) < collection.repeatCount) {
            // New sentence:
            status = SentenceStatus.AGAIN.getStatus();
        }

        return getRandomSentenceByStatus(collection, status, exceptSentenceId);
    }

    private static Sentence getRandomSentenceByStatus(SentenceCollection collection, int status, String exceptSentenceId) {
        List<Sentence> sentences = new Select()
                .from(Sentence.class)
                .where("collection_id=? and status=? and sentence_id!=?", collection.getCollectionID(), status, String.valueOf(exceptSentenceId))
                .orderBy("- complexity")
                .limit(200)
                .execute();
        if (sentences.size() == 0) {
            return null;
        }
        return sentences.get(RANDOM.nextInt(sentences.size()));
    }

    public static void updateStatus(Sentence sentence, SentenceStatus status) {
        sentence.status = status.getStatus();
        sentence.save();

        SentenceHistory h = new SentenceHistory();
        h.sentenceId = sentence.getSentenceId();
        h.status = status.getStatus();
        h.created = System.currentTimeMillis();
        h.save();

        Dao.reloadCollectionCounter(Dao.getCollection(sentence.collectionId));
    }
}

@@ -29,16 +29,46 @@
 ences;%0A%0A
+import android.os.AsyncTask;%0A%0A
 import c
@@ -98,16 +98,16 @@
 Select;%0A
-
 %0Aimport 
@@ -715,58 +715,8 @@
 ) %7B%0A
-        Dao.reloadCollectionCounter(collection);%0A%0A
     
@@ -1662,24 +1662,30 @@
 pdateStatus(
+final 
 Sentence sen
@@ -1986,32 +1986,171 @@
      h.save();%0A%0A
+        new AsyncTask%3CString, Void, Void%3E() %7B%0A            @Override%0A            protected Void doInBackground(String... strings) %7B%0A        
         Dao.relo
@@ -2208,20 +2208,84 @@
 ectionId));%0A
+                return null;%0A            %7D%0A        %7D.execute();%0A
     %7D%0A%7D%0A

Update counter async