package org.sana.android.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import org.sana.android.content.Intents;
import org.sana.android.content.Uris;
import org.sana.android.util.Dates;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by winkler.em@gmail.com, on 03/28/2017.
 */
public class SynchronizationManager {
    public static final String TAG = SynchronizationManager.class.getSimpleName();

    public static void sync(Context context, Uri uri){
        sync(context, uri, null);
    }

    public static void sync(Context context, Uri uri, String keyExtra){
        long last = getLastSynch(context, uri, keyExtra);
        Uri synchUri = uri;
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        calendar.setTimeInMillis(last);
        synchUri = uri.buildUpon().appendQueryParameter("modified__gt",
                    Dates.toSQL(calendar.getTime())).build();

        // Build the synch Intent
        Intent intent = new Intent(Intents.ACTION_READ, synchUri);
        intent.putExtra(Intents.EXTRA_SYNCH, now);
        if(!TextUtils.isEmpty(keyExtra))
            intent.putExtra(Intents.EXTRA_SYNCH_KEY, keyExtra);
        context.startService(intent);
    }

    public static String getSynchKey(Uri uri){
        String type = Uris.getType(uri);
        String[] resolver = type.split("\\.");
        return String.format("%s_sync", resolver[resolver.length - 1].toLowerCase());
    }

    public static String getSynchKey(Uri uri, String suffix){
        String type = Uris.getType(uri);
        String[] resolver = type.split("\\.");
        if(TextUtils.isEmpty(suffix))
            return String.format("%s_sync", resolver[resolver.length - 1].toLowerCase());
        else
            return String.format("%s_%s_sync", resolver[resolver.length - 1].toLowerCase(), suffix);
    }

    public static long getLastSynch(Context context, Uri uri){
        return getLastSynch(context, uri, null);
    }

    public static long getLastSynch(Context context, Uri uri, String keyExtra){
        long last = 0L;
        String key = getSynchKey(uri, keyExtra);
        SharedPreferences preferences =
                PreferenceManager.getDefaultSharedPreferences(context);
        last = preferences.getLong(key, 0L);
        return last;
    }

    public static void setLastSynch(Context context, Uri uri, String keyExtra){
        if(Uris.isItemType(uri)){
            return;
        }
        long synch = 0;
        String synchValue = uri.getQueryParameter("modified__gt");
        if(TextUtils.isEmpty(synchValue)){
            Date now = new Date();
            synch = now.getTime();
        } else {
            try {
                synch = Dates.fromSQL(synchValue).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String key = getSynchKey(uri,keyExtra);
        SharedPreferences preferences =
                PreferenceManager.getDefaultSharedPreferences(context);
        preferences.edit().putLong(key, synch).commit();
    }

    public static void setLastSynch(Context context, Uri uri){
        setLastSynch(context, uri, null);
    }

    public static void setSynchTime(Context context, Uri uri, String keyExtra,
                                    long time){
        if(Uris.isItemType(uri)){
            return;
        }
        String key = getSynchKey(uri,keyExtra);
        SharedPreferences preferences =
                PreferenceManager.getDefaultSharedPreferences(context);
        preferences.edit().putLong(key, time).commit();
    }
}

@@ -1480,32 +1480,57 @@
 chKey(Uri uri)%7B%0A
+        String key = %22%22;%0A
         String t
@@ -1546,32 +1546,75 @@
 s.getType(uri);%0A
+        if(!TextUtils.isEmpty(type)) %7B%0A    
         String%5B%5D
@@ -1656,86 +1656,178 @@
     
-return String.format(%22%25s_sync%22, resolver%5Bresolver.length - 1%5D.toLowerCase()
+    if (resolver.length %3E= 1) %7B%0A                key = resolver%5Bresolver.length - 1%5D.toLowerCase();%0A            %7D%0A        %7D%0A        return String.format(%22%25s_sync%22, key
 );%0A
+%0A
     
@@ -1891,16 +1891,41 @@
 uffix)%7B%0A
+        String key = %22%22;%0A
         
@@ -1949,32 +1949,75 @@
 s.getType(uri);%0A
+        if(!TextUtils.isEmpty(type)) %7B%0A    
         String%5B%5D
@@ -2059,81 +2059,61 @@
     
-if(TextUtils.isEmpty(suffix))%0A            return String.format(%22%25s_sync%22,
+    if (resolver.length %3E= 1) %7B%0A                key =
  res
@@ -2152,17 +2152,16 @@
 erCase()
-)
 ;%0A      
@@ -2162,20 +2162,69 @@
         
-else
+    %7D%0A        %7D%0A        if(TextUtils.isEmpty(suffix))
 %0A       
@@ -2257,61 +2257,84 @@
 %22%25s_
-%25s_
 sync%22, 
-resolver%5Bresolver.length - 1%5D.toLowerCase()
+key);%0A        else%0A            return String.format(%22%25s_%25s_sync%22, key
 , su

Add null value checking to synch keys.