//
//  HistoryViewModel.swift
//  HomeBudget
//
//  Created by Kamil Pieszkur on 19/02/2020.
//  Copyright © 2020 Kamil Pieszkur. All rights reserved.
//

import Foundation
import Firebase

class HistoryViewModel {
    
    var orginalList: [BudgetEntity] = []
    var sumList: [BudgetEntity] = []
    
    func sumListBudget(element: BudgetEntity) {
        sumList.insert(element, at: 0)
    }
    
    func currentMonth() {
        orginalList = sumList
        let currentMonth = sumList.filter { Calendar.current.isDateInThisMonth($0.date ?? Date()) }
        sumList = currentMonth
    }
    
    func setToOrginalList() {
        sumList = orginalList
        orginalList.removeAll()
    }
    
    func remove(element: BudgetEntity) -> Int {
        guard let index = sumList.firstIndex(of: element) else { return 0 }
        
        sumList.remove(at: index)
        return index
    }
    
}

extension HistoryViewModel {

    func get(_ documents: FirebaseDocuments, callback: @escaping (_ resonse: FirebaseRequestResponse) -> Void) {
        ListAPI.readAllLists(from: documents) { [weak self] (documents) in
            self?.sumList = []
            var temp: [BudgetEntity] = []
            documents.forEach { (data) in
                let element = BudgetEntity(data: data)
                temp.insert(element, at: 0)
            }
            self?.sumList = temp.sorted(by: { $0.date?.compare($1.date ?? Date()) == .orderedDescending })
            callback(.success)
        }
    }
}
