@ -3,11 +3,15 @@ package com.cloud.diplomaticquarterapp.utils
import android.app.NotificationChannel
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.Context
import android.content.Intent
import android.content.Intent
import android.os.Build
import android.os.Build
import android.widget.Toast
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.annotation.Nullable
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import androidx.core.app.TaskStackBuilder
import com.cloud.diplomaticquarterapp.BuildConfig
import com.cloud.diplomaticquarterapp.BuildConfig
@ -17,15 +21,17 @@ import com.cloud.diplomaticquarterapp.geofence.GeoZoneModel
import com.cloud.diplomaticquarterapp.geofence.PREFS_STORAGE
import com.cloud.diplomaticquarterapp.geofence.PREFS_STORAGE
import com.cloud.diplomaticquarterapp.geofence.PREF_KEY_HMG_ZONES
import com.cloud.diplomaticquarterapp.geofence.PREF_KEY_HMG_ZONES
import com.cloud.diplomaticquarterapp.geofence.PREF_KEY_LANGUAGE
import com.cloud.diplomaticquarterapp.geofence.PREF_KEY_LANGUAGE
import com.cloud.diplomaticquarterapp.geofence.intent_receivers.ReregisterGeofenceJobService
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.fuel.httpPost
import com.google.android.gms.location.Geofence
import com.google.gson.Gson
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.reflect.TypeToken
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel
import org.jetbrains.anko.doAsyncResult
import org.json.JSONArray
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONException
import org.json.JSONObject
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.*
import kotlin.concurrent.timerTask
import kotlin.concurrent.timerTask
@ -71,7 +77,7 @@ class HMGUtils {
fun getGeoZonesFromPreference ( context : Context ) : List < GeoZoneModel > {
fun getGeoZonesFromPreference ( context : Context ) : List < GeoZoneModel > {
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
val json = pref . getString ( PREF _KEY _HMG _ZONES , " [] " )
val json = pref . getString ( PREF _KEY _HMG _ZONES , " [] " )
val geoZones = GeoZoneModel ( ) . listFrom ( json )
val geoZones = GeoZoneModel ( ) . listFrom ( json )
return geoZones
return geoZones
@ -79,14 +85,14 @@ class HMGUtils {
fun getLanguageCode ( context : Context ) : Int {
fun getLanguageCode ( context : Context ) : Int {
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
val lang = pref . getString ( PREF _KEY _LANGUAGE , " ar " )
val lang = pref . getString ( PREF _KEY _LANGUAGE , " ar " )
return if ( lang == " ar " ) 2 else 1
return if ( lang == " ar " ) 2 else 1
}
}
fun defaultHTTPParams ( context : Context ) : Map < String , Any ? > {
fun defaultHTTPParams ( context : Context ) : Map < String , Any ? > {
return mapOf (
return mapOf (
" ZipCode " to " 966 " ,
" ZipCode " to " 966 " ,
" VersionID " to 5. 6 ,
" VersionID " to 5. 8 ,
" Channel " to 3 ,
" Channel " to 3 ,
" LanguageID " to getLanguageCode ( context ) ,
" LanguageID " to getLanguageCode ( context ) ,
" IPAdress " to " 10.20.10.20 " ,
" IPAdress " to " 10.20.10.20 " ,
@ -97,16 +103,44 @@ class HMGUtils {
" DeviceTypeID " to 2 )
" DeviceTypeID " to 2 )
}
}
fun < T > scheduleJob ( context : Context , pendingIntentClassType : Class < T > , jobId : Int , intervalDuration : String , deadlineMillis : Long = ( 30 * 1000 ) ) { // default deadline: 30 Seconds
if ( android . os . Build . VERSION . SDK _INT >= android . os . Build . VERSION_CODES . M ) {
val jobScheduler : JobScheduler = context . getSystemService ( JobScheduler :: class . java )
val serviceComponent = ComponentName ( context , pendingIntentClassType )
val builder = JobInfo . Builder ( jobId , serviceComponent )
builder . setPersisted ( true )
val intervalMillis = timeToMillis ( intervalDuration , " HH:mm:ss " )
builder . setMinimumLatency ( intervalMillis ) // wait at least
builder . setOverrideDeadline ( ( intervalMillis + deadlineMillis ) ) // maximum delay
if ( jobScheduler . schedule ( builder . build ( ) ) == JobScheduler . RESULT _SUCCESS ) {
Logs . save ( context , " ScheduleJob " , " ${pendingIntentClassType.simpleName} : Job scheduled to trigger after duration $intervalDuration >> HH:mm:ss --('MinimumLatency: $intervalMillis Deadline: ${(intervalMillis + deadlineMillis)} ')-- " , Logs . STATUS . SUCCESS )
} else {
Logs . save ( context , " ScheduleJob " , " ${pendingIntentClassType.simpleName} : Failed to scheduled Job " , Logs . STATUS . ERROR )
}
}
}
} else {
Logs . save ( context , " ScheduleJob " , " ${pendingIntentClassType.simpleName} : Failed to scheduled Job on VERSION.SDK_INT < ${android.os.Build.VERSION_CODES.M} " , Logs . STATUS . ERROR )
}
}
private fun Timer . schedule ( timerTask : TimerTask ) {
}
}
}
private const val NOTIFICATION _CHANNEL _ID = BuildConfig . APPLICATION _ID + " .channel "
private const val NOTIFICATION _CHANNEL _ID = BuildConfig . APPLICATION _ID + " .channel "
fun sendNotification ( context : Context , title : String , @Nullable subtitle : String ? , message : String ? ) {
fun timeToMillis ( time : String , format : String ) : Long {
val sdf = SimpleDateFormat ( format , Locale . US )
val millis = sdf . parse ( time ) . time + TimeZone . getDefault ( ) . rawOffset
return millis
}
fun sendNotification ( context : Context , title : String , @Nullable subtitle : String ? , message : String ? ) {
val notificationManager = context . getSystemService ( Context . NOTIFICATION _SERVICE ) as NotificationManager
val notificationManager = context . getSystemService ( Context . NOTIFICATION _SERVICE ) as NotificationManager
if ( Build . VERSION . SDK _INT >= Build . VERSION_CODES . O
if ( Build . VERSION . SDK _INT >= Build . VERSION_CODES . O
@ -126,7 +160,7 @@ fun sendNotification(context: Context, title:String, @Nullable subtitle:String?,
. addNextIntent ( intent )
. addNextIntent ( intent )
val notificationPendingIntent = stackBuilder . getPendingIntent ( getUniqueId ( ) , PendingIntent . FLAG _UPDATE _CURRENT )
val notificationPendingIntent = stackBuilder . getPendingIntent ( getUniqueId ( ) , PendingIntent . FLAG _UPDATE _CURRENT )
val notification = NotificationCompat . Builder ( context , NOTIFICATION _CHANNEL _ID + " .geofence " )
val notification = NotificationCompat . Builder ( context , NOTIFICATION _CHANNEL _ID )
. setSmallIcon ( R . mipmap . ic _launcher )
. setSmallIcon ( R . mipmap . ic _launcher )
. setContentIntent ( notificationPendingIntent )
. setContentIntent ( notificationPendingIntent )
. setAutoCancel ( true )
. setAutoCancel ( true )
@ -141,7 +175,15 @@ fun sendNotification(context: Context, title:String, @Nullable subtitle:String?,
//-------------------------
//-------------------------
// Open Helper Methods
// Open Helper Methods
//-------------------------
//-------------------------
private fun getUniqueId ( ) = ( ( System . currentTimeMillis ( ) % 10000 ) . toInt ( ) )
fun getUniqueId ( ) = ( ( System . currentTimeMillis ( ) % 10000 ) . toInt ( ) )
object DateUtils {
@JvmStatic
fun dateTimeNow ( ) : String {
val format = SimpleDateFormat ( " dd-MMM-yyy hh:mm:ss " )
return format . format ( Date ( ) )
}
}
fun isJSONValid ( jsonString : String ? ) : Boolean {
fun isJSONValid ( jsonString : String ? ) : Boolean {
try { JSONObject ( jsonString ) } catch ( ex : JSONException ) {
try { JSONObject ( jsonString ) } catch ( ex : JSONException ) {
@ -152,11 +194,16 @@ fun isJSONValid(jsonString: String?): Boolean {
return true
return true
}
}
fun saveLog ( context : Context , tag : String , message : String ) {
fun saveLog ( context : Context , tag : String , message : String ) {
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
var logs = pref . getString ( " GEOFENCE_ LOGS" , " " )
var logs = pref . getString ( " LOGS" , " " )
logs += " $tag -> $message \n "
logs += " $tag -> $message \n "
pref . edit ( ) . putString ( " GEOFENCE_LOGS " , logs ) . apply ( ) ;
pref . edit ( ) . putString ( " LOGS " , logs ) . apply ( ) ;
}
fun getLogs ( context : Context ) : String ? {
val pref = context . getSharedPreferences ( PREFS _STORAGE , Context . MODE _PRIVATE )
return pref . getString ( " LOGS " , " " )
}
}
class HTTPResponse < T > ( data : T ) {
class HTTPResponse < T > ( data : T ) {
@ -170,15 +217,16 @@ fun <T>httpPost(url: String, body: Map<String, Any?>, onSuccess: (response: HTTP
url . httpPost ( )
url . httpPost ( )
. jsonBody ( jsonBody , Charsets . UTF _8 )
. jsonBody ( jsonBody , Charsets . UTF _8 )
. timeout ( 10000 )
. timeout ( 10000 )
. header ( " Content-Type " , " application/json " )
. header ( " Content-Type " , " application/json " )
. header ( " Allow " , " */* " )
. header ( " Allow " , " */* " )
. response { request , response , result ->
. response { request , response , result ->
result . doAsyncResult { }
result . fold ( { data ->
result . fold ( { data ->
val dataString = String ( data )
val dataString = String ( data )
if ( isJSONValid ( dataString ) ) {
if ( isJSONValid ( dataString ) ) {
val responseData = gson . fromJson < T > ( dataString , type )
val responseData = gson . fromJson < T > ( dataString , type )
onSuccess ( HTTPResponse ( responseData ) )
onSuccess ( HTTPResponse ( responseData ) )
} else {
} else {
onError ( Exception ( " Invalid response from server (Not a valid JSON) " ) )
onError ( Exception ( " Invalid response from server (Not a valid JSON) " ) )
}
}
} , {
} , {