//
//  Text.swift
//
//  Copyright © 2020 Apple Inc. All rights reserved.
//


import Foundation
import SPCCore
import SPCScene
import SpriteKit

open class Text: Graphic {
    public enum Alignment {
        case left, right, center, justified
        
        public var textAlignment: NSTextAlignment {
            switch self {
            case .left: return .left
            case .right: return .right
            case .center: return .center
            case .justified: return .justified
            }
        }
    }
    
    public var alignment: Alignment = .left {
        didSet {
            updateTextImage()
        }
    }
    
    public var textColor: Color = .black {
        didSet {
            updateTextImage()
        }
    }
    
    public var text: String = "" {
        didSet {
            updateTextImage()
        }
    }
    
    public var textSize: Size = Size(width: 512, height: 128) {
        didSet {
            updateTextImage()
        }
    }
    public var fontSize: Int = 30 {
        didSet {
            updateTextImage()
        }
    }
    
    public var font: Font = .SystemFontRegular {
        didSet {
            fontName = font.rawValue
            updateTextImage()
        }
    }
    
    public var fontName: String {
        didSet {
            updateTextImage()
        }
    }
    
    public init(_ input: String, size: Size) {
        fontName = font.rawValue
        super.init(graphicType: .label, name: input)
        
        text = input
        textSize = size
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate func updateTextImage() {
        let ff = Font.uiFont(of: fontSize, name: fontName)
        print("**** UIFont = \(ff)")
        let string = text as NSString
        let style = NSMutableParagraphStyle()
        style.alignment = alignment.textAlignment
        let attr: [NSAttributedString.Key: Any] = [
            .font: ff,
            .foregroundColor: textColor,
            .paragraphStyle: style
        ]
        
        let bounds = CGSize(textSize)
        UIGraphicsBeginImageContextWithOptions(bounds, false, 0.0)
        string.draw(in: CGRect(origin: CGPoint.zero, size: bounds), withAttributes: attr)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        guard let textImage = image else { return }
        
        self.texture = SKTexture(image: textImage)
        self.size = CGSize(width: texture!.size().width * CGFloat(xScale), height: texture!.size().height * CGFloat(xScale))
    }
}

extension Font {
    static func uiFont(of size: Int, name: String) -> UIFont {
        if name.starts(with: "System") {
            let weightString = name.replacingOccurrences(of: "System", with: "", options: .literal, range: nil)
            if weightString == "Italic" {
                return UIFont.italicSystemFont(ofSize: CGFloat(size))
            } else if weightString == "BoldItalic" {
                return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight.regular).boldItalic
            } else if weightString == "HeavyItalic" {
                return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight.heavy).italic
            } else {
                if let weight = Double(weightString) {
                    return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight(rawValue: CGFloat(weight)))
                } else {
                    return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight.regular)
                }
            }
        } else {
            if let unwrappedFont = UIFont(name: name, size: CGFloat(size)) {
                return unwrappedFont
            }
            
            return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight.regular)
        }
    }
}
