//
//  Product.swift
//  NearbyStores
//
//  Created by Amine on 5/20/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import RealmSwift

class Product: Object {
    

    @objc dynamic var id: Int = 0
    @objc dynamic var store_id: Int = 0
    @objc dynamic var user_id: Int = 0
    @objc dynamic var status: Int = 0
    @objc dynamic var date_start: String = ""
    @objc dynamic var date_end: String = ""
    @objc dynamic var name: String = ""
    @objc dynamic var store_name: String = ""
    var listImages: List<Images> = List<Images>()
    @objc dynamic var distance: Double = 0
    @objc dynamic var lat: Double = 0
    @objc dynamic var lng: Double = 0
    @objc dynamic var featured: Int = 0
    @objc dynamic var link: String = ""
    @objc dynamic var saved: Bool = false
    
    @objc dynamic var product_type: String = ""
    @objc dynamic var product_value: Double = 0
    @objc dynamic var original_value: Double = 0
    @objc dynamic var currency: Currency? = nil
    @objc dynamic var _description: String = ""
    @objc dynamic var short_description: String = ""
    @objc dynamic var category_id: Int = 0
    var categories: List<Category> = List<Category>()
    
    
    @objc dynamic var is_deal: Int = 0
    @objc dynamic var order_enabled: Int = 0
    @objc dynamic var cf_id: Int = 0
    @objc dynamic var cf: String = ""
    @objc dynamic var order_button: String = ""
    @objc dynamic var stock: Int = 0
    
    
    @objc dynamic var store_order_enabled: Int = 0
    @objc dynamic var store_order_based_on_op: Int = 0
    
    var variants: List<VariantGroup> = List<VariantGroup>()
    
    var fields: List<CustomFields> = List<CustomFields>()
    

    override static func primaryKey() -> String? {
        return "id"
    }
}


extension Product{
    
    func save() {
        if self.id > 0 {
            
            let product = self
            
            let realm = try! Realm()
            realm.beginWrite()
            realm.add(product,update: .all)
            try! realm.commitWrite()
            
        }
    }
    
    static func findById(id: Int) -> Product? {
        
        let realm = try! Realm()
        
        if let product = realm.objects(Product.self).filter("id == \(id)").first {
            return product
        }
        
        return nil
    }
}


