using System;
using System.Json;
using System.Net.Http;
using Foundation;
using System.Threading.Tasks;
using System.Globalization;

[assembly: Xamarin.Forms.Dependency(typeof(InABox.Mobile.iOS.Version_iOS))]
namespace InABox.Mobile.iOS
{
    
    public class Version_iOS : IAppVersion
    {
        string _bundleName => NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleName").ToString();
        string _bundleIdentifier => NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleIdentifier").ToString();
        string _bundleVersion => NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleShortVersionString").ToString();
        JsonValue _appstoreInfo = null;
        
        public string InstalledVersionNumber
        {
            get => _bundleVersion;
        }
        
        public async Task<bool> IsUsingLatestVersion()
        {
            
            try
            {                
                var info = await GetLatestVersion(false);
                return String.IsNullOrWhiteSpace(info.Version) 
                       || (Version.Parse(info.Version).CompareTo(Version.Parse(_bundleVersion)) <= 0);
            }
            catch (Exception e)
            {
                PRS.Mobile.MobileLogging.Log(e,"AppStore");
            }
            return true;
        }


        private async Task CheckAppStoreInfo()
        {
            
            // http://itunes.apple.com/lookup?bundleId=com.prsdigital.prssiteapp
            var url = $"http://itunes.apple.com/lookup?bundleId={_bundleIdentifier}";

            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))
                    {
                        using (var responseMsg = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                        {
                            if (!responseMsg.IsSuccessStatusCode)
                            {
                                throw new LatestVersionException($"Error connecting to the App Store. Url={url}.");
                            }

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

                                _appstoreInfo = JsonValue.Parse(content);

                                
                            }
                            catch (Exception e)
                            {
                                throw new LatestVersionException($"Error parsing content from the App Store. Url={url}.", e);
                            }
                        }
                    }
                }
            }
        }

        private AppInfo _info = null;
        
        public async Task<AppInfo> GetLatestVersion(bool force)
        {
            
            if (force)
                _info = null;

            if (_info != null)
                return _info;
            
            
            _info = new AppInfo();
            try
            {
                await CheckAppStoreInfo();
                if (_appstoreInfo.ContainsKey("results"))
                {
                    var results = _appstoreInfo["results"];
                    if (results.Count > 0)
                    {
                        var result = results[0];
                        if (result.ContainsKey("version"))
                            _info.Version = result["version"];
                        if (result.ContainsKey("releaseDate") && DateTime.TryParse(result["releaseDate"],out DateTime release))
                            _info.Date = release;
                        if (result.ContainsKey("releaseNotes"))
                            _info.Notes = result["releaseNotes"];
                    }
                }
            }
            catch (Exception e)
            {
                MobileLogging.Log(e,"AppStore");
            }
            return _info;

        }

        /// <inheritdoc />
        public Task OpenAppInStore()
        {
            try
            {
                var location = RegionInfo.CurrentRegion.Name.ToLower();
                var trackid = _appstoreInfo["results"][0]["trackId"];
                var url = String.Format("https://itunes.apple.com/{0}/app/{1}/id{2}?mt=8",location,_bundleName,trackid);
                //appName = appName.MakeSafeForAppStoreShortLinkUrl();

#if __IOS__
                
                UIKit.UIApplication.SharedApplication.OpenUrl(new NSUrl(url)); // $"http://appstore.com/{appName}"));
#elif __MACOS__
                AppKit.NSWorkspace.SharedWorkspace.OpenUrl(new NSUrl($"http://appstore.com/mac/{appName}"));
#endif
            }
            catch (Exception e)
            {
                MobileLogging.Log(e);
            }
            return Task.FromResult(true);
        }
    }
}