//  Created by dasdom on 13.04.20.
//  
//

import Foundation

public class BirthdaysManager : ObservableObject {
  public var all: [Birthday] {
    didSet {
      birthdayCounts = all
        .map { BirthdayCountdown(birthday: $0) }
        .sorted(by: { $0.remainingDays < $1.remainingDays })
    }
  }
  @Published public private(set) var birthdayCounts: [BirthdayCountdown]
  
  public init() {
    all = []
    birthdayCounts = []
    
    all = loadBirthdays()
    
    birthdayCounts = all
      .map { BirthdayCountdown(birthday: $0) }
      .sorted(by: { $0.remainingDays < $1.remainingDays })
  }
  
  public func add(_ birthday: Birthday) {
    all.append(birthday)
    save(birthdays: all)
  }
}

public extension BirthdaysManager {
  func save(birthdays: [Birthday]) {
    do {
      let data = try JSONEncoder().encode(birthdays)
      try data.write(to: FileManager.default.birthdaysURL(), options: .atomic)
    } catch {
      print("error: \(error)")
    }
  }
  
  func loadBirthdays() -> [Birthday] {
    do {
      let data = try Data(contentsOf: FileManager.default.birthdaysURL())
      return try JSONDecoder().decode([Birthday].self, from: data)
    } catch {
      return []
    }
  }
}

//  Created by dasdom on 13.04.20.
//  
//

import Foundation

public class BirthdaysManager : ObservableObject {
  public private(set) var all: [Birthday] {
    didSet {
      birthdayCounts = all
        .map { BirthdayCountdown(birthday: $0) }
        .sorted(by: { $0.remainingDays < $1.remainingDays })
    }
  }
  @Published public private(set) var birthdayCounts: [BirthdayCountdown]
  
  public init() {
    all = []
    birthdayCounts = []
    
    all = loadBirthdays()
    
    birthdayCounts = all
      .map { BirthdayCountdown(birthday: $0) }
      .sorted(by: { $0.remainingDays < $1.remainingDays })
  }
  
  public func add(_ birthday: Birthday) {
    all.append(birthday)
    save(birthdays: all)
  }
}

public extension BirthdaysManager {
  func save(birthdays: [Birthday]) {
    do {
      let data = try JSONEncoder().encode(birthdays)
      try data.write(to: FileManager.default.birthdaysURL(), options: .atomic)
    } catch {
      print("error: \(error)")
    }
  }
  
  func loadBirthdays() -> [Birthday] {
    do {
      let data = try Data(contentsOf: FileManager.default.birthdaysURL())
      return try JSONDecoder().decode([Birthday].self, from: data)
    } catch {
      return []
    }
  }
}

--- 
+++ 
@@ -5,7 +5,7 @@
 import Foundation
 
 public class BirthdaysManager : ObservableObject {
-  public private(set) var all: [Birthday] {
+  public var all: [Birthday] {
     didSet {
       birthdayCounts = all
         .map { BirthdayCountdown(birthday: $0) }
Make birthdays changeable from outside
