

import Foundation
import SDWebImageSwiftUI
import SkeletonUI
import SwiftUI

public struct ImageView: View {
    // MARK: Lifecycle

    public init(_ url: String, aspectRatio: CGFloat? = nil, contentMode: ContentMode = ContentMode.fit, placeholder: AnyView? = nil, color: Color? = nil) {
        self.url = url
        self.aspectRatio = aspectRatio
        self.contentMode = contentMode
        self.placeholder = placeholder
        self.color = color
    }

    // MARK: Public

    public var body: some View {
        return WebImage(url: URL(string: url), isAnimating: .constant(true))
            .onFailure { _ in
                error = true
            }
            .onSuccess { _, _, _ in
                error = false
            }
            .resizable()
            .renderingMode(color != nil ? .template : .original)
            .placeholder {
                VStack(alignment: .center, content: {
                    if error {
                        Image("media_fail")
                            .resizable()
                            .renderingMode(.template)
                            .foregroundColor(Colors.black08)
                            .frame(width: 24, height: 24)
                    } else if placeholder != nil {
                        placeholder
                    }
                })
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .skeleton(with: !error && placeholder == nil)
                .shape(type: .rectangle)
            }
            .scaledToFit()
            .transition(.fade)
            .aspectRatio(aspectRatio, contentMode: contentMode)
            .foregroundColor(color)
    }

    // MARK: Internal

    var aspectRatio: CGFloat?
    var contentMode: ContentMode
    var placeholder: AnyView?
    var color: Color?

    @State var error: Bool = false
    var url: String
}

private struct ColorMultiplyModifier: ViewModifier {
    let color: Color?

    func body(content: Content) -> some View {
        if let color {
            content.colorMultiply(color)
        } else {
            content
        }
    }
}
