using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace Valg.EVA.Skanning.UserInterfaceElements.Login
{
    public class HtmlDocument : IHtmlDocument
    {
        private readonly WebBrowser webBrowser;

        public HtmlDocument(WebBrowser webBrowser)
        {
            this.webBrowser = webBrowser;
        }

        public string GetToken()
        {
            return GetFieldValue("accessToken");
        }

        public string GetSignature()
        {
            return GetFieldValue("signature");
        }

        private string GetFieldValue(string fieldName)
        {
            var htmlDocument = webBrowser.Document;

            var allElements = htmlDocument.Body.All;
            var hiddenTokenField = allElements.OfType<HtmlElement>().FirstOrDefault(p => p.Name == fieldName);

            return hiddenTokenField != null ? WebUtility.HtmlDecode(hiddenTokenField.GetAttribute("value")) : null;
        }
    }
}
