import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';

abstract final class RoutineTapFunctionHelper {
  const RoutineTapFunctionHelper._();

  static void onTapFunction(
    BuildContext context, {
    double? step,
    required String functionCode,
    required String functionOperationName,
    required String? functionValueDescription,
    required String? deviceUuid,
    required List<String> codesToAddIntoFunctionsWithDefaultValue,
    int defaultValue = 0,
  }) {
    final functionsBloc = context.read<FunctionBloc>();
    functionsBloc.add(
      SelectFunction(
        functionCode: functionCode,
        operationName: functionOperationName,
      ),
    );
    final addedFunctions = functionsBloc.state.addedFunctions;
    final isFunctionAlreadyAdded = addedFunctions.any(
      (e) => e.functionCode == functionCode,
    );
    final shouldAddFunction =
        codesToAddIntoFunctionsWithDefaultValue.contains(functionCode);
    if (!isFunctionAlreadyAdded && shouldAddFunction) {
      context.read<FunctionBloc>().add(
            AddFunction(
              functionData: DeviceFunctionData(
                entityId: deviceUuid ?? '',
                functionCode: functionCode,
                operationName: functionOperationName,
                value: defaultValue,
                condition: '==',
                valueDescription: functionValueDescription,
              ),
            ),
          );
    }
  }
}
