import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/utils/date_util.dart';
import '../../../data/bean/atmob_track_point.dart';

@injectable
class TrackDetailController extends BaseController {
  static const int lineStart = 1;
  static const int lineEnd = 2;

  final List<AtmobTrackPoint> originPoints = [];
  final RxList<AtmobTrackPoint> pointList = RxList();

  final TextEditingController searchController = TextEditingController();
  final RxString _searchTxt = ''.obs;

  String get searchTxt => _searchTxt.value;

  @override
  void onInit() {
    super.onInit();
    final argument = Get.arguments;
    if (argument != null && argument is List<AtmobTrackPoint>) {
      dealRepeatPoints(argument);
    }
  }

  @override
  void onReady() {
    super.onReady();
    _dealSearchList();
  }

  void dealRepeatPoints(List<AtmobTrackPoint> argument) {
    List<AtmobTrackPoint> newList = [];
    AtmobTrackPoint? last;
    for (int i = 0; i < argument.length; i++) {
      AtmobTrackPoint point = argument[i];
      if (i == 0 || i == argument.length - 1) {
        newList.add(point);
        continue;
      }
      if (last == null) {
        last = point;
        newList.add(point);
      } else if (last.latitude != point.latitude ||
          last.longitude != point.longitude ||
          last.addr != point.addr ||
          DateUtil.isTimeIntRangeExceed(
              point.time, last.time, Duration(seconds: 60))) {
        last = point;
        newList.add(point);
      }
    }

    if (newList.length >= 2) {
      newList.first.traceType = lineStart;
      newList.last.traceType = lineEnd;
    }
    originPoints.assignAll(newList);
  }

  void back() {
    Get.back();
  }

  @override
  void onClose() {
    super.onClose();
    searchController.dispose();
  }

  void onSearch(String txt) {
    _searchTxt.value = txt;
    _dealSearchList();
  }

  void _dealSearchList() {
    if (_searchTxt.value.isEmpty) {
      pointList.clear();
      pointList.addAll(originPoints);
    } else {
      pointList.clear();
      pointList.addAll(originPoints.where((element) {
        return element.addr?.contains(_searchTxt.value) == true;
      }));
    }
  }

  void onClearSearchTxt() {
    searchController.clear();
    _searchTxt.value = '';
    _dealSearchList();
  }
}
