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 bahnplan.web.JSON.ListOrdersResponse;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;

namespace bahnplan.web.Pages {
	public class CardModel : PageModel {
		public void OnPost() {
			if (HttpContext.Session.GetString("authorized") != "true")
				return;

			using var db = new Database.DbConn();
			var request = new XDocument(new XElement("rqorderheadlist",
													 new XElement("rqheader", new XAttribute("ts", "2020-02-19T15:59:00"), new XAttribute("l", "de"),
																  new XAttribute("v", "19120000"), new XAttribute("d", "iPad7,5"),
																  new XAttribute("os", "iOS_13.3.1"), new XAttribute("app", "NAVIGATOR")),
													 new XElement("authlogin", new XAttribute("user", Request.Form["user"]),
																  new XAttribute("pw", Request.Form["pass"]),
																  new XElement("sso", new XAttribute("genToken", "FALSE"))),
													 new XElement("criteria", new XAttribute("validonly", "0")))).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 parsed = ListOrdersResponse.FromJson(json);

			foreach (var order in parsed.Rporderheadlist.Orderheadlist.Orderhead.Where(order => order.On.StartsWith("EBC_"))) {
				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", order.On)),
													 new XElement("authname", new XAttribute("tln", Request.Form["name"])))).ToString();

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

				db.InsertWithInt32Identity(new Card {
					OrderId     = order.On,
					UserId      = int.Parse(HttpContext.Session.GetString("uid")),
					Class       = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "klasse").Text),
					Value       = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "rbs").Text),
					CardNumber  = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "bcnummer").Text,
					CardInfo    = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Txt,
					CardQr      = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text,
					CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text,
					CardImage   = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection,
					Traveller   = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "inhaber").Text,
					ValidFrom   = parsedCard.Rporderdetails.Order.Vfrom,
					ValidTo     = parsedCard.Rporderdetails.Order.Vto,
					QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text,
					QrValidTo   = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text
				});
			}
		}
	}
}