//
//  ModelData.swift
//  Landmarks
//
//  Created by mitulvaghamshi on 2021-07-14.
//

import Foundation

final class ModelData: ObservableObject {
  @Published var landmarks: [Landmark] = load("landmarkData.json")
  @Published var profile = Profile.default
  var hikes: [Hike] = load("hikeData.json")

  var features: [Landmark] {
    landmarks.filter { $0.isFeatured }
  }

  var categories: [String: [Landmark]] {
    Dictionary(
      grouping: landmarks,
      by: { $0.category.rawValue }
    )
  }
}

func load<T: Decodable>(_ filename: String) -> T {
  let data: Data
  
  guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
  else {
    fatalError("Couldn't find \(filename) in main bundle.", file: "ModelData.swift", line: 13)
  }
  
  do {
    data = try Data(contentsOf: file)
  } catch {
    fatalError("Counldn't load \(filename) from main bundle.",file: "ModelData.swift", line: 19)
  }
  
  do {
    let decoder = JSONDecoder()
    return try decoder.decode(T.self, from: data)
  } catch {
    fatalError("Coulden't parse \(filename) as \(T.self):\n\(error)", file: "ModelData.swift", line: 26)
  }
}
