//
//  ProfileImage.swift
//  SimpleX
//
//  Created by Evgeny on 23/03/2022.
//  Copyright © 2022 SimpleX Chat. All rights reserved.
//

import SwiftUI
import SimpleXChat

let defaultProfileImageCorner = 22.5

struct ProfileImage: View {
    var imageStr: String? = nil
    var iconName: String = "person.crop.circle.fill"
    var size: CGFloat
    var color = Color(uiColor: .tertiarySystemGroupedBackground)
    @AppStorage(DEFAULT_PROFILE_IMAGE_CORNER_RADIUS) private var radius = defaultProfileImageCorner

    var body: some View {
        if let image = imageStr,
           let data = Data(base64Encoded: dropImagePrefix(image)),
           let uiImage = UIImage(data: data) {
            clipProfileImage(Image(uiImage: uiImage), size: size, radius: radius)
        } else {
            Image(systemName: iconName)
                .resizable()
                .foregroundColor(color)
                .frame(width: size, height: size)
        }
    }
}

private let squareToCircleRatio = 0.935

private let radiusFactor = (1 - squareToCircleRatio) / 50

@ViewBuilder func clipProfileImage(_ img: Image, size: CGFloat, radius: Double) -> some View {
    let v = img.resizable()
    if radius >= 50 {
        v.frame(width: size, height: size).clipShape(Circle())
    } else if radius <= 0 {
        let sz = size * squareToCircleRatio
        v.frame(width: sz, height: sz).padding((size - sz) / 2)
    } else {
        let sz = size * (squareToCircleRatio + radius * radiusFactor)
        v.frame(width: sz, height: sz)
        .clipShape(RoundedRectangle(cornerRadius: sz * radius / 100, style: .continuous))
        .padding((size - sz) / 2)
    }
}

struct ProfileImage_Previews: PreviewProvider {
    static var previews: some View {
        ProfileImage(imageStr: "data:image/png;base64,[encoded data, 4192 characters]", size: 63)
            .previewLayout(.fixed(width: 63, height: 63))
            .background(.black)
    }
}
