using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MediaBrowser.Api.Images
{
    /// 
    /// Class ImageWriter
    /// 
    public class ImageWriter : IStreamWriter, IHasOptions
    {
        public List Enhancers;
        /// 
        /// Gets or sets the request.
        /// 
        /// The request.
        public ImageRequest Request { get; set; }
        /// 
        /// Gets or sets the item.
        /// 
        /// The item.
        public BaseItem Item { get; set; }
        /// 
        /// The original image date modified
        /// 
        public DateTime OriginalImageDateModified;
        public string OriginalImagePath;
        public IImageProcessor ImageProcessor { get; set; }
        /// 
        /// The _options
        /// 
        private readonly IDictionary _options = new Dictionary();
        /// 
        /// Gets the options.
        /// 
        /// The options.
        public IDictionary Options
        {
            get { return _options; }
        }
        /// 
        /// Writes to.
        /// 
        /// The response stream.
        public void WriteTo(Stream responseStream)
        {
            var task = WriteToAsync(responseStream);
            Task.WaitAll(task);
        }
        /// 
        /// Writes to async.
        /// 
        /// The response stream.
        /// Task.
        private Task WriteToAsync(Stream responseStream)
        {
            var cropwhitespace = Request.Type == ImageType.Logo || Request.Type == ImageType.Art;
            if (Request.CropWhitespace.HasValue)
            {
                cropwhitespace = Request.CropWhitespace.Value;
            }
            var options = new ImageProcessingOptions
            {
                CropWhiteSpace = cropwhitespace,
                Enhancers = Enhancers,
                Height = Request.Height,
                ImageIndex = Request.Index ?? 0,
                ImageType = Request.Type,
                Item = Item,
                MaxHeight = Request.MaxHeight,
                MaxWidth = Request.MaxWidth,
                OriginalImageDateModified = OriginalImageDateModified,
                OriginalImagePath = OriginalImagePath,
                Quality = Request.Quality,
                Width = Request.Width,
                OutputFormat = Request.Format,
                AddPlayedIndicator = Request.AddPlayedIndicator,
                PercentPlayed = Request.PercentPlayed,
                BackgroundColor = Request.BackgroundColor
            };
            return ImageProcessor.ProcessImage(options, responseStream);
        }
    }
}