package org.commcare.utils;

import android.content.SharedPreferences;
import android.text.Spannable;
import android.text.format.DateUtils;
import android.widget.TextView;

import org.commcare.CommCareApplication;
import org.commcare.activities.CommCareHomeActivity;
import org.commcare.adapters.HomeCardDisplayData;
import org.commcare.adapters.SquareButtonViewHolder;
import org.commcare.dalvik.R;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.database.user.models.FormRecord;
import org.javarosa.core.services.locale.Localization;

import java.text.DateFormat;
import java.util.Date;

/**
 * Logic that populates the sync button's notification text
 *
 * @author Phillip Mates (pmates@dimagi.com).
 */
public class SyncDetailCalculations {
    private final static String UNSENT_FORM_NUMBER_KEY = "unsent-number-limit";
    private final static String UNSENT_FORM_TIME_KEY = "unsent-time-limit";

    public static void updateSubText(final CommCareHomeActivity activity,
                                     SquareButtonViewHolder squareButtonViewHolder,
                                     HomeCardDisplayData cardDisplayData) {
        SqlStorage<FormRecord> formsStorage = CommCareApplication._().getUserStorage(FormRecord.class);
        int numUnsentForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_UNSENT).size();
        if (numUnsentForms > 0) {
            Spannable syncIndicator = (activity.localize("home.sync.indicator",
                    new String[]{String.valueOf(numUnsentForms)}));
            squareButtonViewHolder.subTextView.setText(syncIndicator);
            squareButtonViewHolder.subTextView.setTextColor(activity.getResources().getColor(cardDisplayData.subTextColor));
        } else {
            showSyncMessage(squareButtonViewHolder.subTextView,
                    activity.getResources().getColor(cardDisplayData.subTextColor),
                    activity.getResources().getColor(R.color.cc_attention_negative_text),
                    numUnsentForms);
        }
    }

    private static void showSyncMessage(TextView subTextView, int normalColor, int warningColor, int numUnsentForms) {
        CharSequence syncTimeMessage;
        SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
        long lastSyncTime = prefs.getLong("last-succesful-sync", 0);
        if (lastSyncTime == 0) {
            syncTimeMessage = Localization.get("home.sync.message.last.never");
        } else {
            syncTimeMessage = DateUtils.formatSameDayTime(lastSyncTime, new Date().getTime(), DateFormat.DEFAULT, DateFormat.DEFAULT);
        }

        String message = "";
        if (numUnsentForms == 1) {
            message += Localization.get("home.sync.message.unsent.singular") + "\n";
        } else if (numUnsentForms > 1) {
            message += Localization.get("home.sync.message.unsent.plural", new String[]{String.valueOf(numUnsentForms)}) + "\n";
        }

        message += Localization.get("home.sync.message.last", new String[]{syncTimeMessage.toString()});
        subTextView.setText(message);
        if (isSyncStronglyNeeded(numUnsentForms, lastSyncTime)) {
            subTextView.setTextColor(warningColor);
        } else {
            subTextView.setTextColor(normalColor);
        }
    }

    private static boolean isSyncStronglyNeeded(int numUnsentForms, long lastSyncTime) {
        return unsentFormNumberLimitExceeded(numUnsentForms) ||
                unsentFormTimeLimitExceeded(lastSyncTime);
    }

    private static boolean unsentFormNumberLimitExceeded(int numUnsentForms) {
        SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
        int unsentFormNumberLimit = Integer.parseInt(prefs.getString(UNSENT_FORM_NUMBER_KEY, "5"));
        return numUnsentForms > unsentFormNumberLimit;
    }

    private static boolean unsentFormTimeLimitExceeded(long lastSyncTime) {
        SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
        int unsentFormTimeLimit = Integer.parseInt(prefs.getString(UNSENT_FORM_TIME_KEY, "5"));

        long now = new Date().getTime();
        int secs_ago = (int)((lastSyncTime - now) / 1000);
        int days_ago = secs_ago / 86400;

        return ((-days_ago) > unsentFormTimeLimit) &&
                prefs.getString("server-tether", "push-only").equals("sync");
    }
}

@@ -501,16 +501,54 @@
 Record;%0A
+import org.commcare.modern.util.Pair;%0A
 import o
@@ -1190,24 +1190,25 @@
 playData) %7B%0A
+%0A
         SqlS
@@ -1410,24 +1410,107 @@
 NT).size();%0A
+%0A        Pair%3CLong, String%3E lastSyncTimeAndMessage = getLastSyncTimeAndMessage();%0A%0A
         if (
@@ -1746,24 +1746,41 @@
 Indicator);%0A
+        %7D else %7B%0A
             
@@ -1825,164 +1825,178 @@
 Text
-Color(activity.getResources().getColor(cardDisplayData.subTextColor));%0A        %7D else %7B%0A            showSyncMessage(squareButtonViewHolder.subTextView,%0A    
+(lastSyncTimeAndMessage.second);%0A        %7D%0A        setSyncSubtextColor(%0A                squareButtonViewHolder.subTextView, numUnsentForms, lastSyncTimeAndMessage.first,%0A
     
@@ -2079,36 +2079,32 @@
                 
-    
 activity.getReso
@@ -2159,179 +2159,82 @@
 ext)
-,%0A                    numUnsentForms);%0A        %7D%0A    %7D%0A%0A    private static void showSyncMessage(TextView subTextView, int normalColor, int warningColor, int numUnsentForms
+);%0A    %7D%0A%0A    private static Pair%3CLong, String%3E getLastSyncTimeAndMessage(
 ) %7B%0A
@@ -2710,25 +2710,24 @@
       %7D%0A
-%0A
         
 String m
@@ -2722,318 +2722,234 @@
     
-String message = %22%22;%0A        if (numUnsentForms == 1) %7B%0A            message += Localization.get(%22home.sync.message.unsent.singular%22) + %22%5Cn%22;%0A        %7D else if (numUnsentForms %3E 1) %7B
+return new Pair%3C%3E(lastSyncTime, Localization.get(%22home.sync.message.last%22, new String%5B%5D%7BsyncTimeMessage.toString()%7D));
 %0A    
+%7D%0A%0A
     
-    message += Localization.get(%22home.sync.message.unsent.plural%22, new String%5B%5D%7BString.valueOf(numUnsentForms)%7D) + %22%5Cn%22;
+private static void setSyncSubtextColor(TextView subtext, int numUnsentForms, long lastSyncTime,
 %0A   
@@ -2957,19 +2957,16 @@
     
-%7D%0A%0A
         
 mess
@@ -2965,142 +2965,72 @@
     
-message += Localization.get(%22home.sync.message.last%22, new String%5B%5D%7BsyncTimeMessage.toString()%7D);%0A        subTextView.setText(message);
+                            int normalColor, int warningColor) %7B
 %0A   
@@ -3103,32 +3103,28 @@
          sub
-T
+t
 ext
-View
 .setTextColo
@@ -3172,24 +3172,20 @@
      sub
-T
+t
 ext
-View
 .setText

refactor sync subtext setting to be clearer, and to set warning color in both scenarios