namespace MediaBrowser.Model.Drawing
{
    /// 
    /// Class DrawingUtils
    /// 
    public static class DrawingUtils
    {
        /// 
        /// Resizes a set of dimensions
        /// 
        /// The original size object
        /// A new fixed width, if desired
        /// A new fixed height, if desired
        /// A max fixed width, if desired
        /// A max fixed height, if desired
        /// A new size object
        public static ImageSize Resize(ImageSize size,
            double width,
            double height,
            double maxWidth,
            double maxHeight)
        {
            double newWidth = size.Width;
            double newHeight = size.Height;
            if (width > 0 && height > 0)
            {
                newWidth = width;
                newHeight = height;
            }
            else if (height > 0)
            {
                newWidth = GetNewWidth(newHeight, newWidth, height);
                newHeight = height;
            }
            else if (width > 0)
            {
                newHeight = GetNewHeight(newHeight, newWidth, width);
                newWidth = width;
            }
            if (maxHeight > 0 && maxHeight < newHeight)
            {
                newWidth = GetNewWidth(newHeight, newWidth, maxHeight);
                newHeight = maxHeight;
            }
            if (maxWidth > 0 && maxWidth < newWidth)
            {
                newHeight = GetNewHeight(newHeight, newWidth, maxWidth);
                newWidth = maxWidth;
            }
            return new ImageSize { Width = newWidth, Height = newHeight };
        }
        /// 
        /// Gets the new width.
        /// 
        /// Height of the current.
        /// Width of the current.
        /// The new height.
        /// System.Double.
        private static double GetNewWidth(double currentHeight, double currentWidth, double newHeight)
        {
            double scaleFactor = newHeight;
            scaleFactor /= currentHeight;
            scaleFactor *= currentWidth;
            return scaleFactor;
        }
        /// 
        /// Gets the new height.
        /// 
        /// Height of the current.
        /// Width of the current.
        /// The new width.
        /// System.Double.
        private static double GetNewHeight(double currentHeight, double currentWidth, double newWidth)
        {
            double scaleFactor = newWidth;
            scaleFactor /= currentWidth;
            scaleFactor *= currentHeight;
            return scaleFactor;
        }
    }
}