<commit_before>// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Provider;
using Android.Speech;
using Android.Support.V4.Content;
using Android.Widget;
using Newtonsoft.Json;
using SensusService;
using Xamarin;
using SensusService.Probes.Location;
using SensusService.Probes;
using SensusService.Probes.Movement;
using System.Linq;
using ZXing.Mobile;
using Android.Graphics;
using Android.Media;
using Android.Bluetooth;

namespace Sensus.Android
{
    public class AndroidSensusServiceHelper : SensusServiceHelper
    {
        private AndroidSensusService _service;
        private ConnectivityManager _connectivityManager;
        private NotificationManager _notificationManager;
        private string _deviceId;
        private AndroidMainActivity _focusedMainActivity;
        private readonly object _focusedMainActivityLocker = new object();
        private AndroidTextToSpeech _textToSpeech;
        private PowerManager.WakeLock _wakeLock;
        private int _wakeLockAcquisitionCount;
        private List<Action<AndroidMainActivity>> _actionsToRunUsingMainActivity;
        private Dictionary<string, PendingIntent> _callbackIdPendingIntent;
        private bool _userDeniedBluetoothEnable;

        [JsonIgnore]
        public AndroidSensusService Service
        {
            get { return _service; }
        }

        public override string DeviceId
        {
            get { return _deviceId; }
        }

        public override bool WiFiConnected
        {
            get
            {
                // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_21__
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                    return _connectivityManager.GetAllNetworks().Select(network => _connectivityManager.GetNetworkInfo(network)).Any(networkInfo => networkInfo != null && networkInfo.Type == ConnectivityType.Wifi && networkInfo.IsConnected);  // API level 21
                else
#endif
                {
                    // ignore deprecation warning
#pragma warning disable 618
                    return _connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).IsConnected;
#pragma warning restore 618
                }
            }
        }

        public override bool IsCharging
        {
            get
            {
                IntentFilter filter = new IntentFilter(Intent.ActionBatteryChanged);
                BatteryStatus status = (BatteryStatus)_service.RegisterReceiver(null, filter).GetIntExtra(BatteryManager.ExtraStatus, -1);
                return status == BatteryStatus.Charging || status == BatteryStatus.Full;
            }
        }

        public override string OperatingSystem
        {
            get
            {
                return "Android " + Build.VERSION.SdkInt;
            }
        }

        protected override bool IsOnMainThread
        {
            get
            {
                // we should always have a service. if we do not, assume the worst -- that we're on the main thread. this will hopefully
                // produce an error report back at xamarin insights.
                if (_service == null)
                    return true;
                // if we have a service, compare the current thread's looper to the main thread's looper
                else
                    return Looper.MyLooper() == _service.MainLooper;
            }
        }

        public override string Version
        {
            get
            {
                return _service?.PackageManager.GetPackageInfo(_service.PackageName, PackageInfoFlags.Activities).VersionName ?? null;
            }
        }

        [JsonIgnore]
        public int WakeLockAcquisitionCount
        {
            get { return _wakeLockAcquisitionCount; }
        }

        public bool UserDeniedBluetoothEnable
        {
            get
            {
                return _userDeniedBluetoothEnable;
            }

            set
            {
                _userDeniedBluetoothEnable = value;
            }
        }

        public AndroidSensusServiceHelper()
        {
            _actionsToRunUsingMainActivity = new List<Action<AndroidMainActivity>>();
            _callbackIdPendingIntent = new Dictionary<string, PendingIntent>();
            _userDeniedBluetoothEnable = false;
        }

        public void SetService(AndroidSensusService service)
        {
            _service = service;

            if (_service == null)
            {
                if (_connectivityManager != null)
                    _connectivityManager.Dispose();

                if (_notificationManager != null)
                    _notificationManager.Dispose();

                if (_textToSpeech != null)
                    _textToSpeech.Dispose();

                if (_wakeLock != null)
                    _wakeLock.Dispose();
            }
            else
            {
                _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
                _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
                _textToSpeech = new AndroidTextToSpeech(_service);
                _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
                _wakeLockAcquisitionCount = 0;
                _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);

                // must initialize after _deviceId is set
                if (Insights.IsInitialized)
                    Insights.Identify(_deviceId, "Device ID", _deviceId);
            }
        }

        #region main activity

        /// <summary>
        /// Runs an action using main activity, optionally bringing the main activity into focus if it is not already focused.
        /// </summary><commit_msg>Null out objects after dispose to prevent ObjectDisposedException when the objects are used again.<commit_after>// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Provider;
using Android.Speech;
using Android.Support.V4.Content;
using Android.Widget;
using Newtonsoft.Json;
using SensusService;
using Xamarin;
using SensusService.Probes.Location;
using SensusService.Probes;
using SensusService.Probes.Movement;
using System.Linq;
using ZXing.Mobile;
using Android.Graphics;
using Android.Media;
using Android.Bluetooth;

namespace Sensus.Android
{
    public class AndroidSensusServiceHelper : SensusServiceHelper
    {
        private AndroidSensusService _service;
        private ConnectivityManager _connectivityManager;
        private NotificationManager _notificationManager;
        private string _deviceId;
        private AndroidMainActivity _focusedMainActivity;
        private readonly object _focusedMainActivityLocker = new object();
        private AndroidTextToSpeech _textToSpeech;
        private PowerManager.WakeLock _wakeLock;
        private int _wakeLockAcquisitionCount;
        private List<Action<AndroidMainActivity>> _actionsToRunUsingMainActivity;
        private Dictionary<string, PendingIntent> _callbackIdPendingIntent;
        private bool _userDeniedBluetoothEnable;

        [JsonIgnore]
        public AndroidSensusService Service
        {
            get { return _service; }
        }

        public override string DeviceId
        {
            get { return _deviceId; }
        }

        public override bool WiFiConnected
        {
            get
            {
                // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_21__
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                    return _connectivityManager.GetAllNetworks().Select(network => _connectivityManager.GetNetworkInfo(network)).Any(networkInfo => networkInfo != null && networkInfo.Type == ConnectivityType.Wifi && networkInfo.IsConnected);  // API level 21
                else
#endif
                {
                    // ignore deprecation warning
#pragma warning disable 618
                    return _connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).IsConnected;
#pragma warning restore 618
                }
            }
        }

        public override bool IsCharging
        {
            get
            {
                IntentFilter filter = new IntentFilter(Intent.ActionBatteryChanged);
                BatteryStatus status = (BatteryStatus)_service.RegisterReceiver(null, filter).GetIntExtra(BatteryManager.ExtraStatus, -1);
                return status == BatteryStatus.Charging || status == BatteryStatus.Full;
            }
        }

        public override string OperatingSystem
        {
            get
            {
                return "Android " + Build.VERSION.SdkInt;
            }
        }

        protected override bool IsOnMainThread
        {
            get
            {
                // we should always have a service. if we do not, assume the worst -- that we're on the main thread. this will hopefully
                // produce an error report back at xamarin insights.
                if (_service == null)
                    return true;
                // if we have a service, compare the current thread's looper to the main thread's looper
                else
                    return Looper.MyLooper() == _service.MainLooper;
            }
        }

        public override string Version
        {
            get
            {
                return _service?.PackageManager.GetPackageInfo(_service.PackageName, PackageInfoFlags.Activities).VersionName ?? null;
            }
        }

        [JsonIgnore]
        public int WakeLockAcquisitionCount
        {
            get { return _wakeLockAcquisitionCount; }
        }

        public bool UserDeniedBluetoothEnable
        {
            get
            {
                return _userDeniedBluetoothEnable;
            }

            set
            {
                _userDeniedBluetoothEnable = value;
            }
        }

        public AndroidSensusServiceHelper()
        {
            _actionsToRunUsingMainActivity = new List<Action<AndroidMainActivity>>();
            _callbackIdPendingIntent = new Dictionary<string, PendingIntent>();
            _userDeniedBluetoothEnable = false;
        }

        public void SetService(AndroidSensusService service)
        {
            _service = service;

            if (_service == null)
            {
                if (_connectivityManager != null)
                {
                    _connectivityManager.Dispose();
                    _connectivityManager = null;
                }

                if (_notificationManager != null)
                {
                    _notificationManager.Dispose();
                    _notificationManager = null;
                }

                if (_textToSpeech != null)
                {
                    _textToSpeech.Dispose();
                    _textToSpeech = null;
                }

                if (_wakeLock != null)
                {
                    _wakeLock.Dispose();
                    _wakeLock = null;
                }
            }
            else
            {
                _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
                _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
                _textToSpeech = new AndroidTextToSpeech(_service);
                _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
                _wakeLockAcquisitionCount = 0;
                _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);

                // must initialize after _deviceId is set
                if (Insights.IsInitialized)
                    Insights.Identify(_deviceId, "Device ID", _deviceId);
            }
        }

        #region main activity

        /// <summary>
        /// Runs an action using main activity, optionally bringing the main activity into focus if it is not already focused.
        /// </summary>
{'fraction_non_alphanumeric': 0.06732087452197129, 'fraction_numerical': 0.0030305216826610865, 'mean_word_length': 1.964705882352941, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6709694', 'n_tokens_mistral': 3394, 'n_tokens_neox': 3229, 'n_words': 898}