//
//  ChatUrlRawImageView.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2024/07/14.
//

import SwiftUI

struct ChatUrlRawImageView: View {
    var imageUrl: String

    init(message: ChatMessage) {
        var url_string : String = HttpRequestType.RawImage.rawValue
        url_string = url_string.replacingOccurrences(of: "XXXXX", with: String(message.shipId))
        url_string = url_string.replacingOccurrences(of: "YYYYY", with: String(message.messageId))

        self.imageUrl = url_string
    }

    var body: some View {
        VStack {
            AsyncImage(url: URL(string: imageUrl)) { phase in
                if let image = phase.image {
                    image
                        .resizable(resizingMode: .stretch)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 250)
                } else if phase.error != nil {
                    Color.gray.opacity(0.2)
                        .overlay(Image(systemName: "rectangle.slash"))
                } else {
                    Color.gray.opacity(0.2)
                    ProgressView()
                }
            }
            .cornerRadius(16)
            .aspectRatio(contentMode: .fit)
            .frame(height: 250)
        }
        .navigationTitle("image")
    }
}

#Preview {
    ChatUrlRawImageView(message: ChatMessage(
        shipId: 10000003,
        messageId: "92c2dfb5-f5ed-4943-98a3-9848d7f9a962",
        type: 0,
        time: "2023-10-06T01:51:01.872Z",
        location: 1,
        from: "はだだ",
        fromId: "487420489",
        mode: 0,
        message: "999",
        stampId: 0,
        viewer: [
            Viewer(
                time: "2023-10-06T01:51:12.973Z",
                location: 1,
                id: ""),
            Viewer(
                time: "2023-10-06T01:51:12.973Z",
                location: 2,
                id: "")
        ]
    ))
}
