view Simoleon/Helpers/FavouriteButton.swift @ 50:7a6a7c677851

Handle errors with alerts
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Mon, 26 Jul 2021 21:52:15 +0100
parents 75c1a05176f6
children
line wrap: on
line source

//
//  FavouriteButton.swift
//  Simoleon
//
//  Created by Dennis Concepción Martín on 19/07/2021.
//

import SwiftUI

struct FavouriteButton: View {
    var currencyPair: String
    
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: []) private var favourite: FetchedResults<Favourite>
    
    @State private var starSymbol = "star"
    
    var body: some View {
        let favouriteCurrencyPairs = favourite.map { $0.currencyPair }
        Button(action: { favouriteAction(favouriteCurrencyPairs) }) {
            RoundedRectangle(cornerRadius: 15)
                .foregroundColor(Color(.secondarySystemBackground))
                .frame(width: 60, height: 60)
                .overlay(
                    Image(systemName: generateStar(favouriteCurrencyPairs))
                        .font(.system(size: 28))
                        .foregroundColor(Color(.systemYellow))
                )
        }
    }
    
    /*
     If currency pair is favourite:
     * Button action is to remove from favourites
     else:
     * Button action is to add to favourites
     */
    private func favouriteAction(_ favouriteCurrencyPairs: [String]) {
        if favouriteCurrencyPairs.contains(currencyPair) {
            removeFromFavourites()
        } else {
            addToFavourites()
        }
        
        simpleSuccess()
    }
    
    /*
     if currency pair is favourite:
     * Return "star.fill" symbol
     else:
     * Return "star"
     */
    private func generateStar(_ favouriteCurrencyPairs: [String]) -> String {
        if favouriteCurrencyPairs.contains(currencyPair) {
            return "star.fill"
        } else {
            return "star"
        }
    }
    
    /*
     * Get first favourite core data object that matches the specified currency pair
     * Delete it
     */
    private func removeFromFavourites() {
        withAnimation {
            let favouriteObject = favourite.first(where: { $0.currencyPair == currencyPair })
            viewContext.delete(favouriteObject ?? Favourite())
            
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
    
    /*
     * Create a favourite core data object
     * Save it
     */
    private func addToFavourites() {
        withAnimation {
            let favourite = Favourite(context: viewContext)
            favourite.currencyPair = currencyPair
            
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

struct FavouriteButton_Previews: PreviewProvider {
    static var previews: some View {
        FavouriteButton(currencyPair: "USD/GBP")
    }
}