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

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

  JsonViewer({Key? key, required this.title, required this.data}) : super(key: key);

  @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 Text("Rohdaten"),
        content: Text(JsonViewer.format(dataMap)),
        actions: [
          TextButton(onPressed: () => Navigator.of(context).pop(), child: const SingleChildScrollView(child: Text("Schließen")))
        ],
      );
    });
  }
}