using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Helper;

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;
        public InstanceService(IRepository<DicomInstance> instanceRepository, IRepository<DicomStudy> studyRepository,
            IRepository<KeyInstance> keyInstanceRepository )
        {
            _instanceRepository = instanceRepository;
            _studyRepository = studyRepository;
            _keyInstanceRepository = keyInstanceRepository;
        }

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

            var imageResizePath = await _instanceRepository.Where(s => s.SeriesId == seriesId).Select(t=>t.DicomSerie.ImageResizePath).FirstOrDefaultAsync();

            return ResponseOutput.Ok(list, new { ImageResizePath = imageResizePath });
        }


        /// <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;

             path = (await _instanceRepository.Where(s => s.Id == instanceId).Select(t => t.Path).FirstOrDefaultAsync()).IfNullThrowException();

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

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

            //var (physicalPath, relativePath) = FileStoreHelper.GetDicomInstanceFilePath(_hostEnvironment, dicomStudy.TrialId, dicomStudy.SiteId, dicomStudy.SubjectId, dicomStudy.SubjectVisitId, dicomStudy.Id, dicomInstance.Id);

            var physicalPath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, path);

            using (var sw = ImageHelper.RenderPreviewJpeg(physicalPath))
            {
                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;
            var path = (await _instanceRepository.Where(s => s.Id == instanceId).Select(t=>t.Path).FirstOrDefaultAsync()).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
            //var (physicalPath, relativePath) = FileStoreHelper.GetDicomInstanceFilePath(_hostEnvironment, dicomStudy.TrialId, dicomStudy.SiteId, dicomStudy.SubjectId, dicomStudy.SubjectVisitId, dicomStudy.Id, dicomInstance.Id);


            var physicalPath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, path);


            using (var sw = new FileStream(physicalPath, 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");
            }
        }


    }
}