using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Net = Android.Net;


[assembly: Xamarin.Forms.Dependency(typeof(InABox.Mobile.Android.Version_Android))]
namespace InABox.Mobile.Android
{
    /// <summary>
    /// <see cref="ILatestVersion"/> implementation for Android.
    /// </summary>
    [Preserve(AllMembers = true)]
    public class Version_Android : IAppVersion
    {
        string _packageName = "";
        string _versionName = "";


        public Version_Android() : base()
        {
            try
            {
                _packageName = Application.Context.PackageName;
                _versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, 0).VersionName;
            }
            catch
            {

            }
        }

        /// <inheritdoc />
        public string InstalledVersionNumber
        {
            get => _versionName;
        }

        /// <inheritdoc />
        public async Task<bool> IsUsingLatestVersion()
        {
            var latestVersion = string.Empty;

            try
            {
                latestVersion = await GetLatestVersionNumber();

                return Version.Parse(latestVersion).CompareTo(Version.Parse(_versionName)) <= 0;
            }
            catch (Exception e)
            {
                throw new LatestVersionException($"Error comparing current app version number with latest. Version name={_versionName} and lastest version={latestVersion} .", e);
            }
        }

        /// <inheritdoc />
        public async Task<string> GetLatestVersionNumber()
        {
            return await GetLatestVersionNumber(_packageName);
        }

        /// <inheritdoc />
        public async Task<string> GetLatestVersionNumber(string appName)
        {
            if (string.IsNullOrWhiteSpace(appName))
            {
                throw new ArgumentNullException(nameof(appName));
            }

            var version = string.Empty;
            var url = $"https://play.google.com/store/apps/details?id={appName}&hl=en";

            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    using (var handler = new HttpClientHandler())
                    {

                        handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
                        {
                            //bypass
                            return true;
                        };

                        using (var client = new HttpClient(handler))
                        {
                            try
                            {
                                using (var responseMsg = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                                {
                                    if (!responseMsg.IsSuccessStatusCode)
                                    {
                                        throw new LatestVersionException($"Error connecting to the Play Store. Url={url}.");
                                    }

                                    try
                                    {
                                        var content = responseMsg.Content == null ? null : await responseMsg.Content.ReadAsStringAsync();

                                        var versionMatch = Regex.Match(content, "\\[\\[\\[\"(\\d+\\.\\d+\\.\\d+)").Groups[1];                                        

                                        if (versionMatch.Success)
                                        {
                                            version = versionMatch.Value.Trim();
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        throw new LatestVersionException($"Error parsing content from the Play Store. Url={url}.", e);
                                    }
                                }
                            }
                            catch (Exception ex1)
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }

            return version;
        }

        /// <inheritdoc />
        public Task OpenAppInStore()
        {
            return OpenAppInStore(_packageName);
        }

        /// <inheritdoc />
        public Task OpenAppInStore(string appName)
        {
            if (string.IsNullOrWhiteSpace(appName))
            {
                throw new ArgumentNullException(nameof(appName));
            }

            try
            {
                var intent = new Intent(Intent.ActionView, Net.Uri.Parse($"market://details?id={appName}"));
                intent.SetPackage("com.android.vending");
                intent.SetFlags(ActivityFlags.NewTask);
                Application.Context.StartActivity(intent);
            }
            catch (ActivityNotFoundException)
            {
                var intent = new Intent(Intent.ActionView, Net.Uri.Parse($"https://play.google.com/store/apps/details?id={appName}"));
                Application.Context.StartActivity(intent);
            }

            return Task.FromResult(true);
        }
    }
}
