//
//  UITextView+Html.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 16.06.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

extension UITextView {
  func jaq_setHTMLFromString(attr: String) {
    //    attr = attr.stringByAppendingString(NSString(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", "PTSans-bold", font.pointSize) as String)
    self.attributedText = try! NSMutableAttributedString(data: attr.dataUsingEncoding(NSUTF8StringEncoding)!,
                                                         options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)
  }
  
  func link(attr: String, link: String, fontSize: CGFloat = 13, textAlignment: NSTextAlignment = NSTextAlignment.Natural) {
    let style = NSMutableParagraphStyle()
    style.alignment = textAlignment
    let changedAttr = attr.stringByAppendingString(NSString(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", "PTSans-bold", fontSize) as String)
    let ahref = "<a href=\"\(link)\">\(changedAttr)</a>"
    let richText = try! NSMutableAttributedString(data: ahref.dataUsingEncoding(NSUTF8StringEncoding)!,
                                                         options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)
    richText.addAttributes([NSParagraphStyleAttributeName: style], range: NSMakeRange(0, richText.length))
    self.attributedText = richText
  }
}
