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

import Foundation

enum ScrollPositionError: Error {
    case notAPosition
}

extension UICollectionView.ScrollPosition: RawRepresentable {
    
    init?(rawValue: String) {
        switch rawValue {
        case "left", "leading":
            self = .left
        case "centeredHorizontally", "center":
            self = .centeredHorizontally
        case "right", "trailing":
            self = .right
        case "top":
            self = .top
        case "bottom":
            self = .bottom
        case "centeredVertically":
            self = .centeredVertically
        default:
            return nil
        }
    }
    
    
    var rawValueString: String {
        switch self {
        case .left:
            return "left"
        case .centeredHorizontally:
            return "centeredHorizontally"
        case .right:
            return "right"
        case .top:
            return "top"
        case .bottom:
            return "bottom"
        case .centeredVertically:
            return "centeredVertically"
        default:
            return ""
        }
    }
}

extension UICollectionView.ScrollPosition: Codable {
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.singleValueContainer()
        let string = try typeContainer.decode(String.self)
        guard let position = UICollectionView.ScrollPosition(rawValue: string) else {
            throw ScrollPositionError.notAPosition
        }
        self = position
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValueString)
    }
}
