using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using bahnplan.web.database;
using bahnplan.web.database.Tables;
using bahnplan.web.JSON.CardResponse;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;

namespace bahnplan.web.Pages {
	public class CardsModel : PageModel {
		public List<Card> Cards;

		public void OnGet() {
			if (HttpContext.Session.GetString("authorized") != "true")
				return;

			using var db = new Database.DbConn();

			if (Request.Query.ContainsKey("refresh")) {
				var card = db.Cards.First(p => p.CardId == int.Parse(Request.Query["refresh"]));
				if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
					return;

				var request = new XDocument(new XElement("rqorderdetails", new XAttribute("version", "1.0"),
														 new XElement("rqheader", new XAttribute("ts", "2019-10-31T23:20:48"), new XAttribute("l", "de"),
																	  new XAttribute("v", "19100000"), new XAttribute("d", "iPad7,5"),
																	  new XAttribute("os", "iOS_13.1.3"), new XAttribute("app", "NAVIGATOR")),
														 new XElement("rqorder", new XAttribute("on", card.OrderId)),
														 new XElement("authname", new XAttribute("tln", card.Traveller.Split(" ").Last())))).ToString();

				var response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
				var xmlobj   = new XmlDocument();
				xmlobj.LoadXml(response);
				var json       = JsonConvert.SerializeXmlNode(xmlobj);
				var parsedCard = CardResponse.FromJson(json);

				card.CardQr      = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text;
				card.CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text;
				card.CardImage   = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection;
				card.QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text;
				card.QrValidTo   = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text;

				db.Update(card);
				return;
			}

			Cards = db.Cards.Where(p => p.UserId == int.Parse(HttpContext.Session.GetString("uid"))).ToList();
		}
	}
}