//
//  PQObjectMapper+Realm.swift
//  PQSpeed
//
//  Created by ak on 2020/12/3.
//  Copyright © 2020 BytesFlow. All rights reserved.
//  save list data in to realm

import Foundation
import ObjectMapper
import RealmSwift

public struct PQListTransform<T: RealmSwift.Object>: TransformType where T: BaseMappable {
    public typealias Serialize = (List<T>) -> Void
    private let onSerialize: Serialize

    public init(onSerialize: @escaping Serialize = { _ in }) {
        self.onSerialize = onSerialize
    }

    public typealias Object = List<T>
    public typealias JSON = [Any]

    public func transformFromJSON(_ value: Any?) -> List<T>? {
        let list = List<T>()
        if let objects = Mapper<T>().mapArray(JSONObject: value) {
            list.append(objectsIn: objects)
        }
        onSerialize(list)
        return list
    }

    public func transformToJSON(_ value: Object?) -> JSON? {
        return value?.compactMap { $0.toJSON() }
    }
}
