using System.Linq;
using System.Net.Http;
using System.Web.Http;
using log4net;
using OpenCvSharp.CPlusPlus;

namespace Control.Controllers
{
    [RoutePrefix("api/v1/improc")]
    public class CalibrationController : ApiController
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(CalibrationController));

        /// <summary>
        /// This method gets 4x2D points known as Calibration points, which are stored to dictionary with key in form of senders IP address.
        /// </summary>
        /// <param name="port">Application port of robot control gui</param>
        /// <param name="mfd">ID of MFD</param>
        /// <param name="points">Array of Point2f points</param>
        /// <returns>Action result</returns>
        [HttpPost, Route("calibrate/{port?}/{mfd?}")]
        public IHttpActionResult Calibrate(string port, int mfd, [FromBody] Point2f[] points){
            var userIp = Request.GetOwinContext().Request.RemoteIpAddress + ":" + port;
            if (points.Count() != 4){
                Log.Error("Calibration unsuccessful, too few coordinates(" + points.Count() + ")");
                return BadRequest("Number of coordinates must be four, got: " + points.Count());
            }
            if (RqaImProc.CalibrationPoints.ContainsKey(userIp)){
                RqaImProc.CalibrationPoints.Remove(userIp);
            }
            RqaImProc.CalibrationPoints.Add(userIp, new RqaImProc.Values{Mfd = mfd, Points = points});
            Log.Info("Camera was calibrated for IP: " + userIp);
            return Ok();
        }

        /// <summary>
        /// Method indicating calibration status for specific IP and port
        /// </summary>
        /// <param name="port">Application port of robot control gui</param>
        /// <returns>bool</returns>
        [HttpGet, Route("iscalibrated/{port?}")]
        public bool IsCalibrated(string port){
            return RqaImProc.CalibrationPoints.ContainsKey(Request.GetOwinContext().Request.RemoteIpAddress + ":" + port);
        }
    }
}
