import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pretty_json/pretty_json.dart';

class JsonViewer extends StatelessWidget {
  final String title;
  final Map<String, dynamic> data;

  const JsonViewer({super.key, required this.title, required this.data});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Text(format(data)),
      ),
    );
  }
  
  static String format(Map<String, dynamic> jsonInput) {
    return prettyJson(jsonInput, indent: 2);
    //return jsonInput.replaceAllMapped(RegExp(r'[{,}]'), (match) => "${match.group(0)}\n    ");
  }

  static void asDialog(BuildContext context, Map<String, dynamic> dataMap) {
    showDialog(context: context, builder: (context) {
      return AlertDialog(
        scrollable: true,
        title: const Row(children: [Icon(Icons.bug_report_outlined), Text("Rohdaten")]),
        content: Text(JsonViewer.format(dataMap)),
        actions: [
          TextButton(onPressed: () {
            Clipboard.setData(ClipboardData(text: JsonViewer.format(dataMap))).then((value) {
              showDialog(context: context, builder: (context) => const AlertDialog(content: Text("Formatiertes JSON wurde erfolgreich in deiner Zwischenlage abgelegt.")));
            });
          }, child: const Text("Kopieren")),
          TextButton(onPressed: () {
            Clipboard.setData(ClipboardData(text: dataMap.toString())).then((value) {
              showDialog(context: context, builder: (context) => const AlertDialog(content: Text("Unformatiertes JSON wurde erfolgreich in deiner Zwischenablage abgelegt.")));
            });
          }, child: const Text("Inline Kopieren")),
          TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text("Schließen"))
        ],
      );
    });
  }
}
