using IdentityModel.OidcClient.Browser;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AudioWallpaper.SSO {
    public class SystemBrowser : IBrowser {
        private readonly int _port;

        public SystemBrowser(int port) {
            _port = port;
        }

        public async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) {
            var listener = new LoopbackHttpListener(_port, options.EndUrl);

            Process.Start(new ProcessStartInfo {
                FileName = options.StartUrl,
                UseShellExecute = true
            });

            try {
                var result = await listener.WaitForCallbackAsync();
                return new BrowserResult {
                    Response = result,
                    ResultType = BrowserResultType.Success
                };
            } catch (TaskCanceledException) {
                return new BrowserResult {
                    ResultType = BrowserResultType.Timeout,
                    Error = "Login timeout"
                };
            } catch (Exception ex) {
                return new BrowserResult {
                    ResultType = BrowserResultType.UnknownError,
                    Error = ex.Message
                };
            }
        }
    }
}
