//
//  NSTextAlignment+Extension.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 3/24/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

/**
 When using this class in codable for a String value from server.
 
 Example use case....
 
 var alignment: NSTextAlignment
 
 enum CodingKeys: String, CodingKey {
     case alignment
 }
 
 required public init(from decoder: Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
     let word = try container.decode(String.self, forKey: .alignment)
     alignment = NSTextAlignment(rawValue: word)!
 }
 
 public func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     try container.encode(alignment.rawValueString, forKey: .alignment)
 }
 */

enum TextAlignmentError: Error {
    case notAnAlignment
}

extension NSTextAlignment: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "left":
            self = .left
        case "center":
            self = .center
        case "right":
            self = .right
        case "justified":
            self = .justified
        case "natural":
            self = .natural
        default:
            return nil
        }
    }
    
    var rawValueString: String {
        switch self {
        case .left:
            return "left"
        case .center:
            return "center"
        case .right:
            return "right"
        case .justified:
            return "justified"
        case .natural:
            return "natural"
        @unknown default:
            return ""
        }
    }
}

extension NSTextAlignment: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let alignment = NSTextAlignment(rawValue: string) else {
            throw TextAlignmentError.notAnAlignment
        }
        self = alignment
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
