//
//  HtmlText.swift
//  WOKA
//
//  Created by Bilal on 14/06/2024.
//

import Foundation

import UIKit

//MARK : - html Data to Swift Readable
extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}
//MARK : - changing attributed text size without losing html attributes
extension NSMutableAttributedString {
    func setFontFace(font: UIFont, color: UIColor? = nil) {
        beginEditing()
        self.enumerateAttribute(.font,in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
            if let f = value as? UIFont,
               let newFontDescriptor = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
                let newFont = UIFont(descriptor: newFontDescriptor,size: font.pointSize)
                removeAttribute(.font, range: range)
                addAttribute(.font, value: newFont, range: range)
                if let color = color {
                    removeAttribute(.foregroundColor,range: range)
                    addAttribute(.foregroundColor,value: color, range: range)
                }
            }
        }
        endEditing()
    }
}

class AttibutedStringSize {
    static let shareInstance = AttibutedStringSize()
//    func generateAttributedString(targetString: NSAttributedString, selectedNsRange : [NSRange]) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        for range in selectedNsRange{
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
//        }
//        return attributedString
//    }
//
//    func changeFontSize(targetString: NSAttributedString,fontSize : CGFloat) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: fontSize), range: NSRange(location: 0, length: targetString.string.utf16.count))
//        return attributedString
//    }

    func changeDarkOrLightMode(targetString: NSAttributedString,color : UIColor ,selectedNsRange : [NSRange]) -> NSAttributedString? {
        let attributedString = NSMutableAttributedString(attributedString: targetString)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: targetString.string.utf16.count))
        for range in selectedNsRange{
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
        }
        return attributedString
    }
    
    func generateFullyAttributedString(targetString: NSAttributedString, selectedNsRange : [NSRange],selectedLinkNsRange : [NSRange],linkURL:String ,textColor : UIColor , fontSize : CGFloat) -> NSAttributedString?{
        let attributedString = NSMutableAttributedString(attributedString: targetString)
        let range = NSRange(location: 0, length: targetString.string.utf16.count)
        //MARK : - color
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: range)
       
        //MARK : - for selected range with link and underline
        for range1 in selectedLinkNsRange{
            attributedString.addAttribute(.link, value: linkURL, range:range1)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range1)
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range1)
        }
        //MARK : - for highlight the text saved RED Color
        for range2 in selectedNsRange{
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range2)
        }
        //MARK : - for font family and size
        attributedString.setFontFace(font: UIFont.systemFont(ofSize: fontSize))
        return attributedString
    }
    
    func attributedStringSearch(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
        let attributedString = NSMutableAttributedString(attributedString: targetString)
        do {
            let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
            let range = NSRange(location: 0, length: targetString.string.utf16.count)
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)
            for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.green, range: match.range)
            }
            return attributedString
        } catch {
            NSLog("Error creating regular expresion: \(error)")
            return nil
        }
    }
    
//    func generateAttributedStringSearch(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        do {
//            let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
//            let range = NSRange(location: 0, length: targetString.string.utf16.count)
//            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)
//            for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
//                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.green, range: match.range)
//            }
//            return attributedString
//        } catch {
//            NSLog("Error creating regular expresion: \(error)")
//            return nil
//        }
//    }
    
//    func generateAttributedStringColor(targetString: NSAttributedString, color : UIColor) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        let range = NSRange(location: 0, length: targetString.string.utf16.count)
//        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: color, range: range)
//        return attributedString
//    }
    
//    func generateAttributedStringDarkLight(targetString: NSAttributedString, selectedNsRange : [NSRange], color : UIColor,fontSize : CGFloat) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        let fullRange = NSRange(location: 0, length: targetString.string.utf16.count)
//        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Arial", size: fontSize)!, range: fullRange)
//        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: fullRange)
//        for range in selectedNsRange{
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
//        }
//        return attributedString
//    }
    
//    func generateLink(targetString: NSAttributedString ,selectedNsRange : [NSRange], linkURL:String) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        for range in selectedNsRange{
//            attributedString.addAttribute(.link, value: linkURL, range:range)
//            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range)
//        }
//        return attributedString
//    }
    
    //MARK : - for highlight and hyperlink
//    func fullyAttributed(targetString: NSAttributedString ,selectedHighlightRange : [NSRange],selectedLinkRange : [NSRange] ,linkURL:String) -> NSAttributedString? {
//        let attributedString = NSMutableAttributedString(attributedString: targetString)
//        for range in selectedHighlightRange{
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
//        }
//        for range in selectedLinkRange{
//            attributedString.addAttribute(.link, value: linkURL, range:range)
//            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range)
//        }
//
//        return attributedString
//    }
    //MARK : - searchControl

}
//MARK : - attStr To Html


//extension String {
//    func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
//        let attributedString = NSMutableAttributedString(string: self)
//        for string in strings {
//            let range = (self as NSString).range(of: string)
//            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
//        }
//
//        guard let characterSpacing = characterSpacing else {return attributedString}
//
//        attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
//
//        return attributedString
//    }
//}
//
//extension String {
//    public var convertHtmlToNSAttributedString: NSAttributedString? {
//        guard let data = data(using: .utf8) else {
//            return nil
//        }
//        do {
//            return try NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
//        }
//        catch {
//            print(error.localizedDescription)
//            return nil
//        }
//    }
//
//    public func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? {
//        guard let font = font else {
//            return convertHtmlToNSAttributedString
//        }
//        let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)";
//        guard let data = modifiedString.data(using: .utf8) else {
//            return nil
//        }
//        do {
//            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
//        }
//        catch {
//            print(error)
//            return nil
//        }
//    }
//}
