using LISWebAPI.Persistence;
using Microsoft.AspNetCore.Mvc;
using Model.Models.VitrosModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LISWebAPI.Controllers
{
    [ApiController]
    public class VitrosController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;

        public VitrosController(ApplicationDbContext applicationDbContext)
        {
            _dbContext = applicationDbContext;
        }
        [HttpPost]
        [Route("[controller]/[action]")]
        public IActionResult ReceiveSample([FromBody] List<Sample> receivedSamples, [FromQuery] string machineCode)
        {
            // TODO save to database
            // Processing logic

            int machineId = _dbContext.Machines.FirstOrDefault(x => x.MachinedCode == machineCode).Id;

            List<Component> components = _dbContext.ComponentMasterData.Where(x => x.MachineId == machineId).ToList();


            // List<Sample> samples = receivedSamples.Select(vitrosSample => //)

            List<Sample> samples = new List<Sample>();

            foreach (Sample vitrosSample in receivedSamples)
            {
                Sample sample = new Sample()
                {
                    MachineId = machineId,
                    DateTime = vitrosSample.DateTime,
                    TrayName = vitrosSample.TrayName,
                    BarCodeNumber = vitrosSample.BarCodeNumber,
                    Quadrant = vitrosSample.Quadrant,
                    Cup = vitrosSample.Cup,
                    ControlFlag = vitrosSample.ControlFlag,
                    StatFlag = vitrosSample.StatFlag,
                    Mode  = vitrosSample.Mode,
                    DilutionFactor = vitrosSample.DilutionFactor,
                    Fluid = vitrosSample.Fluid,
                    IsActive =  true,
                    Results = vitrosSample.Results.Select(x => new Result()
                    {
                        ComponentMasterId = components.FirstOrDefault(c => c.DisplayName == x.Test).Id,
                        MachineId = machineId,
                        Test = x.Test,
                        Unit = x.Unit,
                        ErrorFlag = x.ErrorFlag,
                        Error = x.Error,
                        WarningFlag = x.WarningFlag,
                        Warning = x.Warning,
                        BarCodeNumber = vitrosSample.BarCodeNumber,
                        IsSync = true,
                        IsActive = true
                    }).ToList()


                };

                samples.Add(sample);
            }



            _dbContext.SampleData.AddRange(samples);
            _dbContext.SaveChanges();

            return Ok(samples);
        }
    }

}
