/*
         *      public void doHistory()
         *      {
         *              var bt = BatchTracking.getNextPeriod("OrderBatch", 15, _acct);
         *              if (bt == null)
         *              {
         *                      System.Threading.Thread.Sleep(60000);
         *                      return;
         *              }
         *              getOrdersFromDateRange(bt.startDate, bt.endDate);
         *              //this will jump us ahead if we make it to end
         *              bt.save();
         *
         *
         *      }
         */
        /*
         *      public void updatePendingOrders()
         *      {
         *
         *              var recs = ShipmentEvent.repo.Query<string>("select distinct amazonorderid from Orders where OrderStatus='Pending' and purchasedate<getdate()-1 and AmazonAccountId = @0", _acct.AmazonAccountId);
         *              var orderIds = recs.ToList();
         *              Log.Error(_acct.AmazonAccountId, $"Got {orderIds.Count()} pending orders to update");
         *              List<string> OrdersToGet = new List<string>();
         *
         *              foreach (var orderID in orderIds)
         *              {
         *                      try
         *                      {
         *                              OrdersToGet.Add(orderID);
         *                              if (OrdersToGet.Count() >= 50)
         *                              {
         *                                      getListOfOrders(OrdersToGet);
         *                                      OrdersToGet = new List<string>();
         *                              }
         *
         *                      }
         *                      catch (Exception e)
         *                      {
         *                              Log.Error(_acct.AmazonAccountId,"getOrdersFromFinancials error", e);
         *                      }
         *
         *              }
         *
         *              if (OrdersToGet.Count() > 0)
         *              {
         *                      getListOfOrders(OrdersToGet);
         *
         *              }
         *      }
         */

        /*
         *      public void getOrdersFromFinancials()
         *      {
         *
         *              var recs = ShipmentEvent.repo.Query<string>("select distinct amazonorderid from shipmentevents  where shipmentevents.AmazonAccountId = @0 and not exists (select * from Orders where orders.amazonorderid = shipmentevents.amazonorderid and orderStatus='Shipped' and Orders.AmazonAccountId=@0) and PostedDate > '2016-01-01'", _acct.AmazonAccountId);
         *              var orderIds = recs.ToList();
         *              List<string> OrdersToGet = new List<string>();
         *
         *              var ttl = orderIds.Count;
         *              var cnt = 0;
         *
         *              foreach (var orderID in orderIds)
         *              {
         *                      cnt++;
         *                      if(cnt%100==0)
         *                              Log.Error(_acct.AmazonAccountId,$"Processed {cnt}/{ttl} missing orders");
         *
         *                      try
         *                      {
         *                              OrdersToGet.Add(orderID);
         *                              if (OrdersToGet.Count() >= 50)
         *                              {
         *                                      getListOfOrders(OrdersToGet);
         *                                      OrdersToGet = new List<string>();
         *                              }
         *
         *                      }
         *                      catch (Exception e)
         *                      {
         *                              Log.Error(_acct.AmazonAccountId, "getOrdersFromFinancials error", e);
         *                      }
         *
         *              }
         *
         *              if (OrdersToGet.Count() > 0)
         *              {
         *                      getListOfOrders(OrdersToGet);
         *
         *              }
         *
         *      }
         */

        public void getOrdersFromDateRange(DateTime startDate, DateTime endDate)
        {
            var startTime = DateTime.Now;

            Log.Info(_acct.AmazonAccountId, $"Preparing to get Order and Details from {startDate} to {endDate} ");

            IDictionary <string, string> r1 = new Dictionary <string, String>();

            r1["Action"]   = "ListOrders";
            r1["SellerId"] = _acct.SellerId;

            r1["MarketplaceId.Id.1"] = _acct.MarketplaceId;

            r1["LastUpdatedAfter"]  = AMZNHelper.GetFormattedTimestamp(startDate);
            r1["LastUpdatedBefore"] = AMZNHelper.GetFormattedTimestamp(endDate);

            //SecureLocalStore.storeItem("lastOrdersDownload", DateTime.Now.ToString());


            AMZNWebResponse wr = new AMZNWebResponse(_acct);


            string s = wr.getResponse(serviceURL, r1);

            var xDoc = XDocument.Parse(s);


            XElement xe = Util.stripNS(xDoc.Elements().First());

            IEnumerable <XElement> Orders = xe.Descendants("Orders").Descendants("Order");

            //Log.Error(_acct.AmazonAccountId, s);


            persistOrders(Orders);


            if (xe.Element("ListOrdersResult") != null && xe.Element("ListOrdersResult").Element("NextToken") != null)
            {
                GetOrdersNextTokens(xe.Element("ListOrdersResult").Element("NextToken").Value);
            }

            var totalMS = (int)(DateTime.Now - startDate).TotalMilliseconds;
            var minMS   = 60 * 1000;           //one minute

            if (minMS - totalMS > 0)
            {
                Thread.Sleep(minMS - totalMS);
            }

            Log.Info(_acct.AmazonAccountId, "Completed getting order and order details");
        }
        public void getOrdersBetween(DateTime startDate, DateTime endDate)
        {
            Log.Info(_acct.AmazonAccountId, $"Preparing to get Order and Details going back from {startDate} to {endDate} ");

            IDictionary <string, string> r1 = new Dictionary <string, String>();

            r1["Action"]   = "ListOrders";
            r1["SellerId"] = _acct.SellerId;

            r1["MarketplaceId.Id.1"] = _acct.MarketplaceId;

            r1["CreatedAfter"]  = AMZNHelper.GetFormattedTimestamp(startDate);
            r1["CreatedBefore"] = AMZNHelper.GetFormattedTimestamp(endDate);


            AMZNWebResponse wr = new AMZNWebResponse(_acct);


            string s = wr.getResponse(serviceURL, r1);

            var xDoc = XDocument.Parse(s);


            XElement xe = Util.stripNS(xDoc.Elements().First());

            IEnumerable <XElement> Orders = xe.Descendants("Orders").Descendants("Order");

            persistOrders(Orders);


            if (xe.Element("ListOrdersResult") != null && xe.Element("ListOrdersResult").Element("NextToken") != null)
            {
                GetOrdersNextTokens(xe.Element("ListOrdersResult").Element("NextToken").Value);
            }

            Log.Info(_acct.AmazonAccountId, "Completed getting order and order details");
        }