//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//
//  The template was designed by Hưng Nguyễn. 
//  Website, application (native/flutter), hosting, SEO.
//  Email: hungnguyen.it36@gmail.com
//  ___COPYRIGHT___
//

import UIKit
import SwiftUI

final class ___VARIABLE_ModuleName___ViewModel: ObservableObject {
    @Published var models: [___VARIABLE_ModuleName___Model] = []
    @Published var loading: Bool = false
    @Published var nextScreen: Bool = false
    var modelSelected: ___VARIABLE_ModuleName___Model? = nil {
        didSet {
            nextScreen = true
        }
    }
    let columns: [GridItem] = [.init(.flexible()), .init(.flexible())]
    let spacing: CGFloat = 10
    let padding: EdgeInsets = EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)
    var canLoadMore: Bool = true
    private var pageIndex = 1
    private let pageSize = 10
    
    private func fetchData() {
        loading = pageIndex == 1
        if pageIndex == 1 {
            models.removeAll()
        }
        let apiUrl = "https://my.api.mockaroo.com/users.json"
        APIRequest.shared.request(urlString: apiUrl, params: ["key": "2a4c4f20"], method: .get) { (result, error) in
            DispatchQueue.main.async  {
                self.loading = false
                guard let jsonData = result else {
                    return
                }
                let models = try? JSONDecoder().decode([___VARIABLE_ModuleName___Model].self, from: jsonData)
                if self.pageIndex == 1 {
                    self.models = models ?? []
                } else if let models = models {
                    self.models.append(contentsOf: models)
                } else {
                    self.canLoadMore = false
                }
            }
        }
    }
    
    func setModelDelected(_ model: ___VARIABLE_ModuleName___Model) {
        modelSelected = model
    }
    
    func refreshData() {
        pageIndex = 1
        fetchData()
    }
    
    func loadMore() {
        pageIndex += 1
        fetchData()
    }
}
