using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Cors;
using System.Net;
using Business.Services.Abstract;
using Common.Models;
using Common.SecurityItems;

namespace DistanceCalculatorApi.Controllers.v1
{
    [EnableCors(SecurityPolicy.SiteCorsPolicy)]
    [ApiController]
    [Route("api/[controller]")]
    public class DistanceController : ControllerBase
    {

        private readonly ILogger<DistanceController> _logger;
        private readonly IDistanceService _distanceService;

        public DistanceController(IDistanceService distanceService, ILogger<DistanceController> logger)
        {
            _distanceService = distanceService;
            _logger = logger;
        }


        /// <summary>
        /// Calculate distance between two ZipCode code
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        [Route("Get")]
        [HttpGet]
        public async Task<IActionResult> GetDistance(string source, string destination)
        {
            var result = await _distanceService.CalculateDistance(source, destination);
            if (string.IsNullOrEmpty(result.Data.SourceAssociateCity) || string.IsNullOrEmpty(result.Data.DestinationAssociateCity))
            {
                result.Data = null;
                result.Message = "Postal codes not found";
                result.Status = Convert.ToInt32(HttpStatusCode.BadRequest);
                return BadRequest(result);
            }
            else
                return Ok(result);
        }


        /// <summary>
        /// Search Zip code 
        /// </summary>
        /// <param name="zipCode"></param>
        /// <returns></returns>
        [Route("Search")]
        [HttpGet]
        public async Task<IActionResult> GetZipCode(string zipCode)
        {
            var result = await _distanceService.GetPostalCode(zipCode);
            if (result.Data.Count > 0)
                return Ok(result);
            else
            {
                result.Data = null;
                result.Message = "Zip code not found";
                result.Status = Convert.ToInt32(HttpStatusCode.BadRequest);
                return BadRequest(result);
            }
        }
    }
}
