using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhilExample.Droid.Services;
using PhilExample.Droid.Utils;
using PhilExample.Services;

[assembly: Xamarin.Forms.Dependency(typeof(ForegroundCrawlService))]
namespace PhilExample.Droid.Services
{
    [Service]
    public class ForegroundCrawlService : Service, IForegroundCrawlService
    {
        private static IForegroundCrawlDelegate _crawlDelegate;
        private static readonly int _notiID = 1;
        private static bool _running = false;

        const string NOTIFICATION_CHANNEL_ID = "1";
        const string NOTIFICATION_CHANNEL_NAME = "PhilExample_noti_1";
        const string NOTIFICATION_CHANNEL_DESCR = "PhilExample_foreground";

        private static System.Threading.Timer _callClock;

        #region IForegroundCrawlService
        public void Start(IForegroundCrawlDelegate del)
        {
            _crawlDelegate = del;

            if (_running)
                UpdateNotification();
            else
            {
                StartService();
                _running = true;
            }
        }

        public void UpdateNotification()
        {
            NotificationHelper.GetAndroidNotificationManager().Notify(_notiID, CreateNotification());
        }

        public void Stop()
        {
            if(_callClock != null)
            {
                _callClock.Dispose();
                _callClock = null;
            }

            //StopForeground(StopForegroundFlags.Remove);
            var fgIntent = new Intent(MainActivity._THIS, typeof(ForegroundCrawlService));
            MainActivity._THIS.StopService(fgIntent);
            _running = false;
        }
        #endregion



        private void StartService()
        {
            var intent = new Intent(MainActivity._THIS, typeof(ForegroundCrawlService));

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                MainActivity._THIS.StartForegroundService(intent);
            else
                MainActivity._THIS.StartService(intent);
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            if (_crawlDelegate == null)
                throw new NotImplementedException("Android ForegroundCrawlService.StartCommandResult");

            Console.WriteLine("Starting foregorund crawl service with _notiID: " + _notiID);
            NotificationHelper.CreateNotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NOTIFICATION_CHANNEL_DESCR);
            //_foregroundNotification = CreateNotification();
            StartForeground(_notiID, CreateNotification());

            var startTimeSpan = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(1);

            _callClock = new System.Threading.Timer((e) =>
            {
                Console.WriteLine("[" + DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + "] (" + _notiID + ") foreground service timer call started");
                _crawlDelegate.Crawl();
                Console.WriteLine("[" + DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + "] (" + _notiID + ") foreground service timer call finished");
            }, null, startTimeSpan, periodTimeSpan);
            return StartCommandResult.Sticky;
        }

        private Notification CreateNotification()
        {
            string msgTitle = _crawlDelegate.GetForegroundNotificationTitle;
            string msgDescr = _crawlDelegate.GetForegroundNotificationDescription;

            Intent notificationIntent = new Intent(MainActivity._THIS, typeof(MainActivity));
            var onClickIntent = PendingIntent.GetActivity(MainActivity._THIS, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);
            var notification = new Notification.Builder(MainActivity._THIS, NOTIFICATION_CHANNEL_ID)
                                    .SetContentIntent(onClickIntent)
                                    .SetContentTitle(msgTitle)
                                    .SetContentText(msgDescr)
                                    .SetSmallIcon(Resource.Drawable.abc_ab_share_pack_mtrl_alpha)
                                    .SetOngoing(true)
                                    .Build();
            return notification;
        }

        public override IBinder OnBind(Intent intent) => null;
    }
}