
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../../api/marianumcloud/talk/chat/getChatResponse.dart';
import '../../../api/marianumcloud/talk/chat/richObjectStringProcessor.dart';
import '../../../model/accountData.dart';
import '../../../model/endpointData.dart';

class ChatMessage {
  String originalMessage;
  Map<String, RichObjectString>? originalData;

  RichObjectString? file;
  String content = "";

  bool get containsFile => file != null;

  ChatMessage({required this.originalMessage, this.originalData}) {
    if(originalData?.containsKey("file") ?? false) {
      file = originalData?['file'];
      content = file?.name ?? "Datei";
    } else {
      content = RichObjectStringProcessor.parseToString(originalMessage, originalData);
    }
  }

  Widget getWidget() {

    if(file == null) {
      return Linkify(
        text: content,
        onOpen: onOpen,
      );
    }

    return CachedNetworkImage(
      errorWidget: (context, url, error) {
        return Column(
          children: [
            const Icon(Icons.image_not_supported_outlined, size: 35),
            Text("Keine Dateivorschau:\n${file!.name}", style: const TextStyle(fontWeight: FontWeight.bold))
          ],
        );
      },
      alignment: Alignment.center,
      placeholder: (context, url) {
        return const Padding(padding: EdgeInsets.all(10), child: CircularProgressIndicator());
      },
      imageUrl: "https://${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().full()}/index.php/core/preview?fileId=${file!.id}&x=100&y=-1&a=1",
    );
  }

  void onOpen(LinkableElement link) async {
    if(await canLaunchUrlString(link.url)) {
      await launchUrlString(link.url);
    } else {

    }
  }
}