//
//  BotManager.swift
//  kt
//
//  Created by neox on 31.10.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import Foundation

//MARK: - Singletone Instance

class BotManager {
    
    //MARK: - Singletone Instance
    let UserDefaultsBotResultsKey = "botResults"
    
    class func sharedInstance() -> BotManager {
        struct Shared {
            static let sharedInstance = BotManager()
        }
        return Shared.sharedInstance
    }
    
    //MARK: - Constructors
    
    private init() {
        
    }
    
    //MARK: - Functions
    func archiveAll(items:[BotResult]) -> NSData {
        let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(items as NSArray)
        return archivedObject
    }
    
    func retrieveAll() -> [BotResult]? {
        if let unarchiveObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsBotResultsKey + UserManager.sharedInstance().login!) as? NSData {
            let existing = NSKeyedUnarchiver.unarchiveObjectWithData(unarchiveObject) as? [BotResult]
            var result = [BotResult]()
            let now = NSDate()
            let dayAgo = now.addDays(-1)
            
            for i in 0 ..< existing!.count {
                let botResult = existing![i]
                print(botResult.date)
                if ( !dayAgo.isGreaterThanDate(botResult.date) ) {
                    result.append(botResult)
                } else {
                    // the rest don't get persisted
                }
            }
            return result
        }
        return nil
    }
    
    func saveStoreFastPay(botResults : [BotResult]) {
        let archivedItems = archiveAll(botResults)
        NSUserDefaults.standardUserDefaults().setObject(archivedItems, forKey: UserDefaultsBotResultsKey + UserManager.sharedInstance().login!)
        NSUserDefaults.standardUserDefaults().synchronize()
    }
    
    func add(botResult : BotResult) {
        var items = retrieveAll()
        if (items == nil) {
            items = []
        }
        items!.append(botResult)
        saveStoreFastPay(items!)
    }
    
}
