//
//  Created by Jim van Zummeren on 05/05/16.
//  Copyright © 2016 M2mobi. All rights reserved.
//

import Foundation
import UIKit

class InlineImageAttributedStringBlockBuilder: LayoutBlockBuilder<NSMutableAttributedString> {

    init(asyncImageHandler: AsyncImageHandler) {
        self.asyncImageHandler = asyncImageHandler
    }

    // MARK: LayoutBuilder

    override func relatedMarkDownItemType() -> MarkDownItem.Type {
        return ImageMarkDownItem.self
    }

    override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<NSMutableAttributedString>, styling: ItemStyling) -> NSMutableAttributedString {
        let imageMarkDownItem = markDownItem as! ImageMarkDownItem

        var attachment: NSTextAttachment?

        if let image = UIImage(named: imageMarkDownItem.file) {
            attachment = TextAttachment()
            attachment?.image = image
        } else if let url = URL(string: imageMarkDownItem.file) {
            attachment = AsyncImageAttachment(
                imageURL: url.addHTTPSIfSchemeIsMissing(),
                asyncImageHandler: asyncImageHandler
            )
        }

        guard let attachment = attachment else {
            return NSMutableAttributedString()
        }

        let mutableAttributedString = NSAttributedString(attachment: attachment)

        return mutableAttributedString as! NSMutableAttributedString
    }

    // MARK: - Private

    private let asyncImageHandler: AsyncImageHandler
}
