using MeteoWebApp.Data;
using MeteoWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace MeteoWebApp.Controllers
{
    public class ApiController : Controller
    {

        private readonly MeteoDbContext _db;

        /* Database context is created in Startup.cs */
        public ApiController(MeteoDbContext db)
        {
            _db = db;
            /* Sets cultureinfo to unify decimal characters with station data */ 
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
        }

        /*  Api for receiving data from station 
         *  Model StationData corrensponds with data sended by station and automaticaly fill data to variables which is used in this method 
         *  Received data are processed and stored to database
         *  This is a place where the data is provided with a time stamp
         */
        [HttpPost]
        public IActionResult LastMeasurement(StationData stationData) 
        {   
            if (ModelState.IsValid)
            {
                // Take api key from request and compare to existing keys in db Stations
                if(_db.Stations.Where(s => s.ApiKey == stationData.ApiKey).Any())
                {
                    // From table Station get StationId which has assigned coresponding api key
                    int stationId = _db.Stations.Where(s => s.ApiKey == stationData.ApiKey).Select(s => s.StationId).Single();
               
                    Measurement newMeasurement = new Measurement(stationData, stationId);

                    // Add new measurent to database
                    _db.Measurements.Add(newMeasurement);
                    _db.SaveChanges();

                    return Ok("Thank you for data :)");
                }
                else
                {
                    return BadRequest("Invalid API key");
                }
            }
            else 
            {
                return BadRequest("Invalid data");
            }
        }

        /*  Api for sending data
         *  Model LastMeasurement is returned in JSON format
         */
        [HttpGet]
        public LastMeasurement LastMeasurement(int stationId)
        {
            // Check if there is any records in database for selected station
            if (_db.Measurements.Where(m => m.StationId == stationId).Any() && _db.Stations.Where(m => m.StationId == stationId).Any())
            {
                DateTime before24H = DateTime.Now.AddHours(-24);
                DateTime before7D = DateTime.Now.AddDays(-7);

                // Pass selected station and last measurement to fill last measurement object
                LastMeasurement lastMeasurement = new LastMeasurement(_db.Measurements.Where(m => m.StationId == stationId).OrderByDescending(m => m.MeasurementId).First(), _db.Stations.Where(s => s.StationId == stationId).First());

                // Insert data which needs more database values selections
                // Calculate sum of rain amount for these two time periods
                lastMeasurement.RainAmount24H = (float)_db.Measurements.Where(m => m.StationId == stationId && m.Timestamp > before24H).Select(m => m.RainAmount).Sum();
                lastMeasurement.RainAmount7D = (float)_db.Measurements.Where(m => m.StationId == stationId && m.Timestamp > before7D).Select(m => m.RainAmount).Sum();

                return lastMeasurement;
            }
            else 
            {
                return null;
            }
        }
    }
}
