import 'package:flutter/material.dart';

import 'package:pshared/provider/payment/amount.dart';


class PaymentCommentFieldController extends ChangeNotifier {
  final TextEditingController textController;

  PaymentAmountProvider? _provider;
  bool _isSyncingText = false;

  PaymentCommentFieldController({required String initialComment})
    : textController = TextEditingController(text: initialComment);

  void update(PaymentAmountProvider provider) {
    if (identical(_provider, provider)) {
      _syncTextWithComment(provider.comment);
      return;
    }
    _provider?.removeListener(_handleProviderChanged);
    _provider = provider;
    _provider?.addListener(_handleProviderChanged);
    _syncTextWithComment(provider.comment);
  }

  void handleChanged(String value) {
    if (_isSyncingText) return;
    _provider?.setComment(value);
  }

  void _handleProviderChanged() {
    final provider = _provider;
    if (provider == null) return;
    _syncTextWithComment(provider.comment);
  }

  void _syncTextWithComment(String comment) {
    if (textController.text == comment) return;
    _isSyncingText = true;
    textController.value = TextEditingValue(
      text: comment,
      selection: TextSelection.collapsed(offset: comment.length),
    );
    _isSyncingText = false;
  }

  @override
  void dispose() {
    _provider?.removeListener(_handleProviderChanged);
    textController.dispose();
    super.dispose();
  }
}
