//
//  PhotoListViewModel.swift
//  CareAxiom MVVM Assignment
//
//  Created by Sobhan Asim on 12/09/2021.
//


import Foundation

final class PhotoListViewModel: NSObject {
    
    var albums: [PhotoAlbumModel] = []
    
    func getNumberOfAlbums() -> Int {
        return albums.count
    }
    
    func getNumberOfPhotos(atSection section: Int) -> Int {
        return albums[section].photos?.count ?? 0
    }
    
    override init() {
        
    }
    
    init(photos: [PhotoModel]?) {
        if let photosArr = photos {
            if let lastAlbumNumber = photos?.last?.albumId {
                self.albums.removeAll()
                for i in 1...lastAlbumNumber {
                    let album: PhotoAlbumModel = PhotoAlbumModel.initPhotoAlbum(fromPhotos: photosArr.filter({($0.albumId ?? -1) == i}))
                    
                    self.albums.append(album)
                }
            }
        }
    }
    
    
    func getImagesData(with handler: @escaping (_ photos: [PhotoModel]?, _ error: Error?) -> Void){
        PhotoFetcher.invokePhotoListAPIReuest { photos, error in
            if let error = error {
                handler(nil, error)
            } else if let photosArr = photos {
                handler(photosArr, nil)
            }
        }
    }
    
    func objectForItemAtIndexPath(indexPath: IndexPath) -> PhotoModel?{
        return self.albums[indexPath.section].photos?[indexPath.row]
    }
    
}

