using IRaCIS.Core.Application.Contracts.Dicom;
using IRaCIS.Core.Application.Contracts.Dicom.DTO;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Dicom;
using Microsoft.AspNetCore.Authorization;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Infrastructure.Extention;

namespace IRaCIS.Core.Application.Services
{
    [ApiExplorerSettings(GroupName = "Image")]
    [AllowAnonymous]
    public class InstanceService : BaseService, IInstanceService
    {
        private readonly IRepository<DicomInstance> _instanceRepository;
        private readonly IRepository<DicomStudy> _studyRepository;
        private readonly IRepository<KeyInstance> _keyInstanceRepository;
        private readonly DicomFileStoreHelper _dicomFileStoreHelper;
        public InstanceService(IRepository<DicomInstance> instanceRepository, IRepository<DicomStudy> studyRepository,
            IRepository<KeyInstance> keyInstanceRepository, DicomFileStoreHelper dicomFileStoreHelper)
        {
            _dicomFileStoreHelper = dicomFileStoreHelper;
            _instanceRepository = instanceRepository;
            _studyRepository = studyRepository;
            _keyInstanceRepository = keyInstanceRepository;
        }

        /// <summary> 指定资源Id，获取Dicom序列所属的实例信息列表 </summary>
        /// <param name="seriesId"> Dicom序列的Id </param>
        [HttpGet("{seriesId:guid}")]
        public async Task<IEnumerable<DicomInstanceDTO>> List(Guid seriesId)
        {
            return await _instanceRepository.Where(s => s.SeriesId == seriesId).OrderBy(s => s.InstanceNumber).
                ThenBy(s => s.InstanceTime).ThenBy(s => s.CreateTime)
                .ProjectTo<DicomInstanceDTO>(_mapper.ConfigurationProvider).ToListAsync();
        }


        /// <summary> 指定资源Id，获取Dicom序列所属的实例Id列表 </summary>
        /// <param name="seriesId"> Dicom序列的Id </param>
        /// <param name="tpCode"></param>
        /// <param name="key"></param>
        [HttpGet, Route("{seriesId:guid}/{tpCode?}/{key?}")]
        public IEnumerable<Guid> List(Guid seriesId, string tpCode, bool? key)
        {
            if (key != null && key.HasValue && key.Value)
            {
                return _keyInstanceRepository.Where(s => s.TpCode == tpCode).Select(t => t.InstanceId).Distinct();
            }
            else
                return _instanceRepository.Where(s => s.SeriesId == seriesId).OrderBy(s => s.InstanceNumber).Select(t => t.Id);
        }

        [AllowAnonymous]
        [HttpGet, Route("{instanceId:guid}")]
        public async Task<FileContentResult> Preview(Guid instanceId)
        {
            var path = string.Empty;

            DicomInstance dicomInstance = await _instanceRepository.FirstOrDefaultAsync(s => s.Id == instanceId).IfNullThrowException();

            DicomStudy dicomStudy = await _studyRepository.FirstOrDefaultAsync(s => s.Id == dicomInstance.StudyId).IfNullThrowException();

            path = _dicomFileStoreHelper.GetInstanceFilePath(dicomStudy, dicomInstance.SeriesId, dicomInstance.Id.ToString());



            using (var sw = DicomRenderingHelper.RenderPreviewJpeg(path))
            {
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, "image/jpeg");
            }
        }

        [AllowAnonymous]
        [HttpGet, Route("{instanceId:guid}")]
        public async Task<FileContentResult> Content(Guid instanceId)
        {
            var filePath = string.Empty;
            DicomInstance dicomInstance = await _instanceRepository.FirstOrDefaultAsync(s => s.Id == instanceId).IfNullThrowException();

            DicomStudy dicomStudy = await _studyRepository.FirstOrDefaultAsync(s => s.Id == dicomInstance.StudyId).IfNullThrowException();


            if (dicomInstance.Anonymize) //被匿名化
            {
                filePath = _dicomFileStoreHelper.GetInstanceFilePath(dicomStudy, dicomInstance.SeriesId, dicomInstance.Id + ".Anonymize");
            }

            else filePath = _dicomFileStoreHelper.GetInstanceFilePath(dicomStudy, dicomInstance.SeriesId, dicomInstance.Id.ToString());



            using (var sw = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, "application/octet-stream");
            }
        }


    }
}