//
//  NSTextAttachment+Emoji.swift
//  Tusker
//
//  Created by Shadowfacts on 3/1/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import UIKit

extension NSTextAttachment {
    // Based on https://github.com/ReticentJohn/Amaroq/blob/7c5b7088eb9fd1611dcb0f47d43bf8df093e142c/DireFloof/InlineImageHelpers.m
    @available(iOS, deprecated: 15.0)
    convenience init(emojiImage image: UIImage, in font: UIFont, with textColor: UIColor = .label) {
        let adjustedCapHeight = font.capHeight - 1
        var imageSizeMatchingFontSize = CGSize(width: image.size.width * (adjustedCapHeight / image.size.height), height: adjustedCapHeight)
        
        let defaultScale: CGFloat = 1.4
        imageSizeMatchingFontSize = CGSize(width: imageSizeMatchingFontSize.width * defaultScale, height: imageSizeMatchingFontSize.height * defaultScale)
        
        let attachmentImage = UIGraphicsImageRenderer(size: imageSizeMatchingFontSize).image { (_) in
            textColor.set()
            image.draw(in: CGRect(origin: .zero, size: imageSizeMatchingFontSize))
        }
        
        self.init(image: attachmentImage)
    }
    
    convenience init(emojiPlaceholderIn font: UIFont) {
        let adjustedCapHeight = font.capHeight - 1
        // assumes emoji are mostly square
        let size = CGSize(width: adjustedCapHeight, height: adjustedCapHeight)
        let image = UIGraphicsImageRenderer(size: size).image { (_) in }
        self.init(image: image)
    }
}
