using Domain.BaseData;
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Models.BaseData;
using Services.BaseData;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Api.Controllers
{
    [Authorize(Roles = Consts.Developer)]
    public class MiscellaneousImagesController : BaseController
    {
        private readonly IMiscellaneousImageService miscellaneousImageService;

        public MiscellaneousImagesController(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            miscellaneousImageService = serviceProvider.GetService<IMiscellaneousImageService>();
        }

        [HttpGet]
        public IActionResult List()
        {
            var dbList = miscellaneousImageService.GetQueryable().ToList();
            return Ok(Mapper.Map<List<MiscellaneousImageViewModel>>(dbList));
        }

        [HttpPost]
        public IActionResult Add(SaveMiscellaneousImageViewModel model)
        {
            var dbModel = Mapper.Map<MiscellaneousImage>(model);
            var imageName = SaveImageFromBase64(model.Base64Image);
            dbModel.ImageFileName = imageName;
            miscellaneousImageService.Add(dbModel);
            return Ok();
        }

        [HttpPut]
        public IActionResult Update(MiscellaneousImageViewModel model)
        {
            var dbModel = miscellaneousImageService.GetById(model.Id.Value);
            Mapper.Map(model, dbModel);
            miscellaneousImageService.Update(dbModel);
            return Ok();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(Guid id)
        {
            if (!miscellaneousImageService.CanBeDeleted(id))
            {
                return BadRequest("This image is used in other records and can not be deleted.");
            }
            miscellaneousImageService.Delete(id);
            return Ok();
        }
    }
}
