import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:flutter_background/flutter_background.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  _MyHomePageState() {
    timer =
        Timer.periodic(const Duration(microseconds: 2500), _updateDataSource);
  }

  Timer? timer;
  List<_ChartData>? chartData;
  late int count;
  ChartSeriesController? _chartSeriesController;
  final androidConfig = const FlutterBackgroundAndroidConfig(
    notificationTitle: "flutter_background example app",
    notificationText:
        "Background notification for keeping the example app running in the background",
    notificationImportance: AndroidNotificationImportance.Default,
    notificationIcon: AndroidResource(
        name: 'background_icon',
        defType: 'drawable'), // Default is ic_launcher from folder mipmap
  );

  @override
  void dispose() {
    timer?.cancel();
    chartData!.clear();
    _chartSeriesController = null;
    super.dispose();
  }

  @override
  void initState() {
    initializeBackgroundRun().then((value) => startBgService());
    count = 19;
    chartData = <_ChartData>[
      _ChartData(0.0, 42.0),
      _ChartData(1.0, 47.0),
      _ChartData(2.0, 33.0),
      _ChartData(3.0, 49.0),
      _ChartData(4.0, 54.0),
      _ChartData(5.0, 41.0),
      _ChartData(6.0, 58.0),
      _ChartData(7.0, 51.0),
      _ChartData(8.0, 98.0),
      _ChartData(9.0, 41.0),
      _ChartData(10.0, 53.0),
      _ChartData(11.0, 72.0),
      _ChartData(12.0, 86.0),
      _ChartData(13.0, 52.0),
      _ChartData(14.0, 94.0),
      _ChartData(15.0, 92.0),
      _ChartData(16.0, 86.0),
      _ChartData(17.0, 72.0),
      _ChartData(18.0, 94.0),
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(), body: _buildLiveLineChart());
  }

  /// Returns the realtime Cartesian line chart.
  SfCartesianChart _buildLiveLineChart() {
    return SfCartesianChart(
        plotAreaBorderWidth: 0,
        zoomPanBehavior: ZoomPanBehavior(enablePanning: true,enablePinching: true),
        primaryXAxis:
            NumericAxis(majorGridLines: const MajorGridLines(width: 0)),
        primaryYAxis: NumericAxis(
            axisLine: const AxisLine(width: 0),
            majorTickLines: const MajorTickLines(size: 0)),
        series: <LineSeries<_ChartData, double>>[
          LineSeries<_ChartData, double>(
            onRendererCreated: (ChartSeriesController controller) {
              _chartSeriesController = controller;
            },
            dataSource: chartData!,
            color: const Color.fromRGBO(192, 108, 132, 1),
            xValueMapper: (_ChartData sales, _) => sales.country,
            yValueMapper: (_ChartData sales, _) => sales.sales,
            animationDuration: 0,
          )
        ]);
  }

  ///Continously updating the data source based on timer
  void _updateDataSource(Timer timer) {
    chartData!
        .add(_ChartData(count.toDouble(), _getRandomInt(10, 10000).toDouble()));
    if (chartData!.length == 20) {
      _chartSeriesController?.updateDataSource(
        addedDataIndexes: <int>[chartData!.length - 1],
      );
    } else {
      _chartSeriesController?.updateDataSource(
        addedDataIndexes: <int>[chartData!.length - 1],
      );
    }
    count = count + 1;
  }

  ///Get the random data
  int _getRandomInt(int min, int max) {
    final math.Random _random = math.Random();
    return min + _random.nextInt(max - min);
  }

  Future<void> initializeBackgroundRun() async {
    if (Platform.isAndroid) {
      bool success =
          await FlutterBackground.initialize(androidConfig: androidConfig);
    }
  }

  Future<void> startBgService() async {
    if (Platform.isAndroid) {
      bool success = await FlutterBackground.enableBackgroundExecution();
    }
  }
}

class _ChartData {
  _ChartData(this.country, this.sales);
  final double country;
  final double sales;
}
