using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;
using rockfishCore.Util;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Linq;

namespace rockfishCore.Controllers
{
    //### OUR ROUTE CALLED FROM ROCKFISH CLIENT ####
    [Produces("application/json")]
    [Route("api/order")]

    public class OrderController : Controller
    {
        private readonly rockfishContext ct;


        public OrderController(rockfishContext context)
        {
            ct = context;
        }




        //Receive an order notification from ShareIt
        [HttpPost("shareit")]
        public async Task<IActionResult> Post([FromHeader] string Authorization, [FromBody] JObject j)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                //do stuff with the notification
                (string username, string password) = rockfishCore.Util.AutoOrderProcessingUtil.GetUsernameAndPasswordFromAuthorizeHeader(Authorization);
                // Now use username and password with whatever authentication process you want 
                if (username == "Y24PYYDQSA1L12905N5MKU" && password == "MA8GMQK2PC3FDNT1RTR68R")
                {
                    //put the jobject notification into the db as json string freeform notification information
                    //to be processed by other code later.  i.e. just capture it as is cleanly and don't bother trying to do anything fancy here this should be tight and focused and side effect free

                    //save it to the database
                    var VendorNotification = new VendorNotification();
                    VendorNotification.Vendor = "shareit";
                    VendorNotification.Data = j.ToString();
                    VendorNotification.Processed = false;
                    await ct.VendorNotification.AddAsync(VendorNotification);
                    await ct.SaveChangesAsync();
                }


            }
            catch (Exception ex)
            {
                //todo Log this here
                System.Diagnostics.Debug.WriteLine($"order/shareit - Exception processing request: {ex.Message}");
            }

            return Ok("ok");//shareit robot looks for an OK response to know if it should resend or not https://account.mycommerce.com/home/wiki/7479805

        }


        [HttpGet("list/{siteId}")]
        public async Task<IActionResult> GetList([FromRoute] long siteId)
        {
            return Ok(await ct.License.AsNoTracking().Where(z => z.SiteId == siteId).OrderByDescending(z => z.Id).ToListAsync());
        }




    }//eoc
}//eons