import 'package:flutter/material.dart';
import 'package:segmentation_douglas_peucker_flutter/dali_point.dart';
import 'package:segmentation_douglas_peucker_flutter/douglas.dart';
import 'package:segmentation_douglas_peucker_flutter/sketcher_line.dart';
import 'package:segmentation_douglas_peucker_flutter/sketcher_points.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Main(),
        ),
      ),
    );
  }
}

class Main extends StatefulWidget {
  const Main({super.key});

  @override
  State<Main> createState() => _MainState();
}

class _MainState extends State<Main> {
  List<DaliPoint> _points = [];
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: [
        Listener(
          behavior: HitTestBehavior.opaque,
          onPointerMove: (event) {
            setState(() {
              _points.add(
                DaliPoint(
                  event.localPosition.dx.toInt(),
                  event.localPosition.dy.toInt(),
                ),
              );
            });
          },
          child: SizedBox(
            width: MediaQuery.sizeOf(context).width,
            height: MediaQuery.sizeOf(context).height,
            child: Stack(
              children: [
                CustomPaint(
                  painter: SketcherLine(
                    points: _points,
                  ),
                ),
                CustomPaint(
                  painter: SketcherPoints(
                    points: _points,
                  ),
                ),
              ],
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(32),
          child: ElevatedButton(
            onPressed: () {
              final newPoints = Douglas.transformDouglasPeucker(_points);
              setState(() {
                _points = newPoints;
              });
            },
            child: const Text('Apply Douglas Peucker'),
          ),
        )
      ],
    );
  }
}
