using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AudioWallpaper.SSO {
    public class LoopbackHttpListener {
        private readonly string _url;
        private readonly string _redirectUri;

        public LoopbackHttpListener(int port, string redirectUri) {
            _redirectUri = redirectUri;
            _url = $"http://127.0.0.1:{port}/";
        }

        public async Task<string> WaitForCallbackAsync() {
            using var listener = new HttpListener();
            listener.Prefixes.Add(_url);
            listener.Start();

            var context = await listener.GetContextAsync();
            var request = context.Request;

            var response = context.Response;
            response.Headers.Add("Content-Type", "text/html; charset=UTF-8");
            string responseString = "<html><body><h1>登录成功！请返回应用程序。</h1></body></html>";
            var buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();

            listener.Stop();
            return request.Url.ToString();
        }
    }
}
