//
//  Order.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/11/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import RealmSwift



class Order: Object{
    
    @objc dynamic var id: Int = 0
    @objc dynamic var user_id: Int = 0
    @objc dynamic var status: String = ""
    @objc dynamic var created_at: String = ""
    @objc dynamic var payment_status: String = ""
    @objc dynamic var invoice: Int = 0
    @objc dynamic var amount: Double = 0
    @objc dynamic var delivery_status: Int = 0
    @objc dynamic var extras: String = ""
    
    
    @objc dynamic var extrasValue: Double = 0.0
    @objc dynamic var discountsValue: Double = 0.0
    @objc dynamic var taxesValue: Double = 0.0
    
    

    var items: List<OrderItem> = List<OrderItem>()
    var timeline: List<TLPoint> = List<TLPoint>()
    
    @objc dynamic var store_id: Int = 0
    @objc dynamic var delivery_id: Int = 0
   
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
    var is_open = false

}



class TLPoint : Object{
    
    @objc dynamic var id: String = ""
    @objc dynamic var date: String = ""
    @objc dynamic var status: String = ""
    @objc dynamic var message: String = ""
    @objc dynamic var order_id: Int = 0
    @objc dynamic var managed_by: String = ""
    
    override static func primaryKey() -> String? {
        return "id"
    }
}


class Cart : Object{
    
    @objc dynamic var id: Int = 1
    var items: List<OrderProduct> = List<OrderProduct>()
    
    
    static func hasStore(item0: OrderProduct) -> Bool {
        
        if let cart = Cart.find(){
            
            for item in cart.items{
                if(item.item?.store_id != item0.item?.store_id){
                    return false
                }
            }
            
        }
        
        return true
    }
    
    static func openCart(items: [OrderProduct]) -> Cart {
    
        guard let cart = Cart.find() else {
            
            let cart = Cart()
    
            let realm = try! Realm()
            realm.beginWrite()
            
            cart.id = 1
            
            for i in items{
                cart.items.append(i)
            }
            
            try! realm.commitWrite()
            
            cart.save()
            
            return cart
        }
        
        let realm = try! Realm()
        realm.beginWrite()
        
        for i in items{
            cart.items.append(i)
        }
        
        try! realm.commitWrite()
        
        
        cart.save()
        

        return cart
       
    }
    
    static func createCart(id: Int,items: [OrderProduct]) -> Cart {
    
        if let cart = Cart.find(id: id){
            
            let realm = try! Realm()
            realm.beginWrite()
            
            cart.items = List<OrderProduct>()
            
            for i in items{
                cart.items.append(i)
            }
            
            try! realm.commitWrite()
            
            cart.save()
            
            return cart
        }
       
        
        let cart = Cart()
        cart.id = 2
      
        let realm = try! Realm()
        realm.beginWrite()
        
        for i in items{
            cart.items.append(i)
        }
        
        try! realm.commitWrite()
        
        cart.save()
        
        
        return cart
        
       
    }
    
    
    static func clear() {
        
        let realm = try! Realm()
       
        let result = realm.objects(Cart.self)
        realm.beginWrite()
        realm.delete(result)
        try! realm.commitWrite()
        
        
    }
    
   
    static func removeProduct(id: Int) {
        let realm = try! Realm()
       
        let result = realm.objects(OrderProduct.self).filter("id == \(id)")
        realm.beginWrite()
        realm.delete(result)
        try! realm.commitWrite()
    }
    
   
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
    
    func save() {
        if self.id > 0 {
            let order = self
            let realm = try! Realm()
            realm.beginWrite()
            realm.add(order,update: .all)
            try! realm.commitWrite()
        }
    }
    
    static func find() -> Cart? {
        
        let realm = try! Realm()
        if let order = realm.objects(Cart.self).filter("id == \(1)").first {
            return order
        }
        return nil
    }
    
    static func find(id: Int) -> Cart? {
        
        let realm = try! Realm()
        if let order = realm.objects(Cart.self).filter("id == \(id)").first {
            return order
        }
        return nil
    }
}


class OrderProduct : Object {
   
    static func nextID() -> Int{
        return Int.random(in: 1..<1000000)
    }

    
    @objc dynamic var id: Int = OrderProduct.nextID()
    @objc dynamic var item: Product? = nil
    @objc dynamic var qty: Int = 1
    @objc dynamic var amount: Double = 0
    var variants: List<V_GroupResult> = List<V_GroupResult>()
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
    
    static func findById(id: Int) -> OrderProduct? {
        
        let realm = try! Realm()
        
        if let order = realm.objects(OrderProduct.self).filter("id == \(id)").first {
            return order
        }
        
        return nil
    }
}




class OrderItem: Object{
    
    @objc dynamic var id: Int = 0
    @objc dynamic var oi_id: String = ""
    @objc dynamic var module: String = ""
    @objc dynamic var image: String = ""
    @objc dynamic var name: String = ""
    @objc dynamic var amount: Double = 0
    @objc dynamic var Qty: Double = 0
    @objc dynamic var currency: Currency?
 
    override static func primaryKey() -> String? {
        return "oi_id"
    }

}


class OrderPayment: Object{
    
    @objc dynamic var id: String = ""
    @objc dynamic var method: String = ""
    @objc dynamic var image: String = ""
    @objc dynamic var payment_desctiption: String = ""
    @objc dynamic var tax: OrderPaymentTax?
 
    override static func primaryKey() -> String? {
        return "id"
    }
    
    
       static func removeAll() {
           
           let realm = try! Realm()
           
           let result: Results<OrderPayment> = realm.objects(OrderPayment.self)
           
           realm.beginWrite()
           realm.delete(result)
           try! realm.commitWrite()
       }
       

}

class OrderPaymentTax: Object{
    
    @objc dynamic var id: Int = 0
    @objc dynamic var value: Double = 0.0
    @objc dynamic var name: String = ""
 
    override static func primaryKey() -> String? {
        return "id"
    }
    

}






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


extension Array where Element:Order {
    
    func saveAll(){
        
        let orders: [Order] = self
        
        if orders.count > 0 {
            
            let realm = try! Realm()
            
            realm.beginWrite()
            realm.add(orders,update: .all)
            try! realm.commitWrite()
            
        }
        
    }
    
    
    func getindex(order_id: Int) -> Int? {
        
        var orders: [Order] = self
        
        
        //resfresh item to the top
        let size = orders.count - 1
        
        if size >= 0 {
            
            for index in 0...size {
                
                if orders[index].id == order_id{
                    return index
                }
                
            }
            
        }
        
        
        return nil
        
    }
        
}




extension Array where Element:OrderPayment {

    func saveAll(){
       
        let objects: [OrderPayment] = self
        
        if objects.count > 0 {
            
            let realm = try! Realm()
            
            realm.beginWrite()
            realm.add(objects,update: .all)
            try! realm.commitWrite()
            
        }
        
    }
}


extension RealmCollection
{
  func toArray<T>() ->[T]
  {
    return self.compactMap{$0 as? T}
  }
}


extension Array
{
  func toRealmList<T>() -> List<T>
  {
    var list =  List<T>()
    
    for item in self {
        list.append(item as! T)
    }
    
    return list
  }
}


