using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace NoName_CarplateRecognizeCamera_Lab.Controllers
{
    [Route("api/[controller]")]
    public class CameraDataController : Controller
    {
        static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Application");

        public static Action<SimplaCarPlateRecognizeResult> OnCarPlateRead;
        [HttpPost]
        public async Task<IActionResult> Post([FromBody]SimplaCarPlateRecognizeResult value)
        {
            try
            {
                if (value == null)
                {
                    logger.Info("null or invalid car plate data");
                    // for test purpose
                    //OnCarPlateRead?.Invoke(new SimplaCarPlateRecognizeResult()
                    //{
                    //    AlarmInfoPlate = new AlarmInfoPlate()
                    //    {
                    //        result = new result() { PlateResult = new PlateResult() { license = "testę³°BD8734" } }
                    //    }
                    //});
                }
                else
                {
                    logger.Info("Read carPlate: " + value.AlarmInfoPlate.result.PlateResult.license);
                    OnCarPlateRead?.Invoke(value);
                    if (!string.IsNullOrEmpty(CameraApp.SmsServiceUrl))
                    {
                        logger.Info("   will send SMS");
                        var formatedUrl = string.Format(CameraApp.SmsServiceUrl, value.AlarmInfoPlate.result.PlateResult.license);
                        var webRequest = HttpWebRequest.Create(formatedUrl);
                        var webResponse = (webRequest.GetResponse() as HttpWebResponse);
                        logger.Info("        SMS service returned with Code: " + webResponse.StatusCode + ", ContentLen: " + webResponse.ContentLength);
                    }
                }
            }
            catch (Exception exx)
            {
                logger.Error("CameraDataController Post(...) exceptioned: " + exx);
            }

            return Ok();
        }
        //var formatedUrl = "http://wc.shaojun.xyz:8585/api/shortMessage/carPlateNumber/" + HttpUtility.UrlEncode(recognized.AlarmInfoPlate.result.PlateResult.license) + "/phoneNumber/" + HttpUtility.UrlEncode("13817741205,13774352835");
        //var webRequest =
        //    HttpWebRequest.Create(formatedUrl);
        //var webResponse = (webRequest.GetResponse() as HttpWebResponse);
        //Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  remote service returned with HttpStatusCode: " + webResponse.StatusCode + ", Content - Len: " + webResponse.ContentLength);
    }
}