//
//  LinkPreview.swift
//  SimpleX
//
//  Created by Ian Davies on 04/04/2022.
//  Copyright © 2022 SimpleX Chat. All rights reserved.
//

import SwiftUI
import LinkPresentation
import SimpleXChat

func getLinkPreview(url: URL, cb: @escaping (LinkPreview?) -> Void) {
    logger.debug("getLinkMetadata: fetching URL preview")
    LPMetadataProvider().startFetchingMetadata(for: url){ metadata, error in
        if let e = error {
            logger.error("Error retrieving link metadata: \(e.localizedDescription)")
        }
        if let metadata = metadata,
           let imageProvider = metadata.imageProvider,
           imageProvider.canLoadObject(ofClass: UIImage.self) {
            imageProvider.loadObject(ofClass: UIImage.self){ object, error in
                var linkPreview: LinkPreview? = nil
                if let error = error {
                    logger.error("Couldn't load image preview from link metadata with error: \(error.localizedDescription)")
                } else {
                    if let image = object as? UIImage,
                       let resized = resizeImageToStrSize(image, maxDataSize: 14000),
                       let title = metadata.title,
                       let uri = metadata.originalURL {
                        linkPreview = LinkPreview(uri: uri, title: title, image: resized)
                    }
                }
                cb(linkPreview)
            }
        } else {
            cb(nil)
        }
    }
}

struct ComposeLinkView: View {
    @Environment(\.colorScheme) var colorScheme
    let linkPreview: LinkPreview?
    var cancelPreview: (() -> Void)? = nil
    let cancelEnabled: Bool

    var body: some View {
        HStack(alignment: .center, spacing: 8) {
            if let linkPreview = linkPreview {
                linkPreviewView(linkPreview)
            } else {
                ProgressView()
                    .padding(.leading, 12)
                    .frame(maxWidth: .infinity, minHeight: 60, maxHeight: 60, alignment: .leading)
            }
            if let cancelPreview = cancelPreview, cancelEnabled {
                Button { cancelPreview() } label: {
                    Image(systemName: "multiply")
                }
            }
        }
        .padding(.vertical, 1)
        .padding(.trailing, 12)
        .background(colorScheme == .light ? sentColorLight : sentColorDark)
        .frame(maxWidth: .infinity)
        .padding(.top, 8)
    }

    private func linkPreviewView(_ linkPreview: LinkPreview) -> some View {
        HStack(alignment: .center, spacing: 8) {
            if let data = Data(base64Encoded: dropImagePrefix(linkPreview.image)),
               let uiImage = UIImage(data: data) {
                Image(uiImage: uiImage)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(maxWidth: 80, maxHeight: 60)
            }
            VStack(alignment: .center, spacing: 4) {
                Text(linkPreview.title)
                    .lineLimit(1)
                Text(linkPreview.uri.absoluteString)
                    .font(.caption)
                    .lineLimit(1)
                    .foregroundColor(.secondary)
            }
            .padding(.vertical, 5)
            .frame(maxWidth: .infinity, minHeight: 60, maxHeight: 60)
        }
    }
}

struct SmallLinkPreview_Previews: PreviewProvider {
    static var previews: some View {
        let preview = LinkPreview(
            uri: URL(string: "http://DuckDuckGo.com")!,
            title: "Privacy, simplified.",
            description: "",
            image: "data:image/jpg;base64,[encoded data, 8224 characters]"
        )
        Group {
            ComposeLinkView(linkPreview: preview, cancelPreview: {}, cancelEnabled: true)
                .previewLayout(.fixed(width: 360, height: 200))
            ComposeLinkView(linkPreview: nil, cancelPreview: {}, cancelEnabled: true)
                .previewLayout(.fixed(width: 360, height: 200))
        }
    }
}
