//
//  BasketViewModel.swift
//  FoodPool
//
//  Created by Ayşe Nur Bakırcı on 18.08.2021.
//

import Extensions
import RestaurantAPI

public protocol BasketViewModelProtocol {
    
    func load()
    func meal(indexPath: Int) -> RestaurantMenuModel?
    var numberOfItemsMeal: Int { get }
    var totalPrice: String { get }
    var delegate: BasketViewModelDelegate? { get set }
}

public protocol BasketViewModelDelegate: AnyObject {
    func reloadData()
}

public final class BasketViewModel {
    
    public init() {}
    
    private var basketModel: [RestaurantMenuModel] = []
    private var total: Double = 0.0
    
    weak public var delegate: BasketViewModelDelegate?

    fileprivate func getMealsInBasket() {
        
        total = 0.0

        for meal in basketModel {
            total += Double(meal.price) ?? 0.0
        }
        
        delegate?.reloadData()
    }
    
}

extension BasketViewModel: BasketViewModelProtocol {
    
    public func load() {
        getMealsInBasket()
    }
    
    public func meal(indexPath: Int) -> RestaurantMenuModel? {
        basketModel[safe: indexPath]
    }
    
    public var totalPrice: String {
        "\(total)$"
    }
    
    public var numberOfItemsMeal: Int {
        basketModel.count
    }
}
