using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Expo.Server.Client;
using Expo.Server.Models;
using FMSAdmin.Data;

namespace FMSAdmin.Helpers {
    public class PushHelper {
        private readonly ILogger<PushHelper> _logger;
        private readonly FMSContext _context;


        public PushHelper(
            ILogger<PushHelper> logger,
            FMSContext context
        ) {
            _logger = logger;
            _context = context;
        }


        public void SendToSiteUsers(int siteId, string title, string message, object data) {
            var tokens = _context.CmUser.Where(
                x => x.SiteId == siteId
                && x.IsUse == true
                && !string.IsNullOrEmpty(x.Devicetoken)
            ).Select(x => x.Devicetoken).ToList();

            _logger.LogInformation("<<<<<<<< SendToSiteUsers");
            _logger.LogInformation("Title : " + title);
            _logger.LogInformation("Message : " + message);
            _logger.LogInformation("Tokens => ");
            foreach (var token in tokens) {
                _logger.LogInformation(token);
            }
            _logger.LogInformation(">>>>>>>>>>>>>>>>>>>>>>>>");

            var expoClient = new PushApiClient();
            var request = new PushTicketRequest() {
                PushTo = tokens,
                PushTitle = title,
                PushBody = message,
                PushData = data
            };
            var result = expoClient.PushSendAsync(request).GetAwaiter().GetResult();
            if (result?.PushTicketErrors?.Count() > 0) {
                foreach (var error in result.PushTicketErrors) {
                    _logger.LogError($"SendToSiteUsers Error : {error.ErrorCode} - {error.ErrorMessage}");
                }
            }
        }

        public void SendToAllUsers(string title, string message, object data) {
            var tokens = _context.CmUser.Where(
                x => x.IsUse == true
                && !string.IsNullOrEmpty(x.Devicetoken)
            ).Select(x => x.Devicetoken).ToList();

            var expoClient = new PushApiClient();
            var request = new PushTicketRequest() {
                PushTo = tokens,
                PushTitle = title,
                PushBody = message,
                PushData = data
            };
            var result = expoClient.PushSendAsync(request).GetAwaiter().GetResult();
            if (result?.PushTicketErrors?.Count() > 0) {
                foreach (var error in result.PushTicketErrors) {
                    _logger.LogError($"SendToAllUsers Error : {error.ErrorCode} - {error.ErrorMessage}");
                }
            }
        }

    }
}
