import 'dart:convert';
import 'package:filesize/filesize.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jiffy/jiffy.dart';
import 'package:localstore/localstore.dart';
import 'package:marianum_mobile/screen/settings/debug/jsonViewer.dart';

class DebugOverview extends StatefulWidget {
  const DebugOverview({Key? key}) : super(key: key);

  @override
  State<DebugOverview> createState() => _DebugOverviewState();
}

class _DebugOverviewState extends State<DebugOverview> {

  final Localstore storage = Localstore.instance;
  Future<Map<String, dynamic>?> files = Localstore.instance.collection("MarianumMobile").get();
  dynamic data;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Lokaler cache"),
      ),
      body: Column(
        children: [
          ListTile(
            leading: const Icon(Icons.delete_forever),
            title: const Text("Cache löschen"),
            onTap: () {
              PaintingBinding.instance.imageCache.clear();
              storage.collection("MarianumMobile").delete().then((value) => {
                Navigator.pop(context)
              });
            },
          ),

          const Divider(),
          FutureBuilder(
            future: files,
            builder: (context, snapshot) {
              if(snapshot.hasData) {
                List<String> files = snapshot.data?.keys.map((e) => e.toString()).toList() ?? List<String>.empty();

                Map<String, dynamic> getValue(int index) {
                  return snapshot.data?[files[index]];
                }

                return Expanded(
                  flex: 5,
                  child: ListView.builder(
                    itemCount: files.length,
                    itemBuilder: (context, index) {
                      String filename = files[index].split("/").last;

                      return ListTile(
                        leading: const Icon(Icons.text_snippet_outlined),
                        title: Text(filename),
                        subtitle: Text("${filesize(getValue(index).toString().length * 8)}, ${Jiffy.unixFromMillisecondsSinceEpoch(getValue(index)['lastupdate']).fromNow()}"),
                        trailing: Icon(Icons.chevron_right),
                        textColor: Colors.black,
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return JsonViewer(title: filename, data: {"lastupdate": getValue(index)['lastupdate'], "json": jsonDecode(getValue(index)['json'])});
                          },));
                        },
                        onLongPress: () {
                          showDialog(context: context, builder: (context) {
                            return SimpleDialog(
                              children: [
                                ListTile(
                                  leading: Icon(Icons.delete_forever),
                                  title: Text("Diese Datei löschen"),
                                ),
                                ListTile(
                                  leading: Icon(Icons.copy),
                                  title: Text("Dateitext kopieren"),
                                  onTap: () {
                                    Clipboard.setData(ClipboardData(text: getValue(index).toString()));
                                    Navigator.of(context).pop();
                                  },
                                )
                              ],
                            );
                          });
                        },
                      );
                    },
                  ),
                );
              } else {
                return snapshot.data == null ? const Text("No data") : const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ],
      ),
    );
  }
}