//
//  Cardify.swift
//  MemoryCardGame
//
//  Created by Felipe on 03/10/21.
//

import SwiftUI

struct Cardify: AnimatableModifier {
    var rotation: Double
    var isMatched: Bool
    var color: Color
    
    init(isFaceUp: Bool, isMatched: Bool, color: Color) {
        self.rotation = isFaceUp ? 0 : 180
        self.isMatched = isMatched
        self.color = color
    }
    
    var animatableData: Double {
        get {
            return rotation
        }
        set {
            self.rotation = newValue
        }
    }
    
    let cardShape = RoundedRectangle(cornerRadius: DrawingConstants.cornerRadius)
    func body(content: Content) -> some View {
        ZStack {
            cardShape.fill(color).opacity(not(isVisible()))
            
            Group {
                cardShape.fill(DrawingConstants.backgroundColor)
                cardShape
                    .strokeBorder(lineWidth: DrawingConstants.strokeSize)
                    .foregroundColor(isMatched ? Color.green : color)
            }
            .opacity(isVisible())
            
            content
                .opacity(isVisible())
        }
        .rotation3DEffect(
            Angle.degrees(rotation),
            axis: (x: 0.0, y: 1.0, z: 0.0)
            )
    }
    
    fileprivate func isVisible() -> Double {
        return rotation < 90 ? 1 : 0
    }
    
    fileprivate func not(_ input: Double) -> Double {
        return input == 0 ? 1 : 0
    }
}


extension View {
    func cardify(isFaceUp: Bool, isMatched: Bool, color: Color) -> some View {
        self.modifier(Cardify(isFaceUp: isFaceUp, isMatched: isMatched, color: color))
    }
}
