import 'package:flutter/cupertino.dart';
import 'package:flutter_contacts/flutter_contacts.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/data/consts/error_code.dart';
import 'package:location/data/repositories/account_repository.dart';
import 'package:location/data/repositories/urgent_contact_repository.dart';
import 'package:location/handler/error_handler.dart';
import 'package:location/module/member/member_page.dart';
import 'package:location/utils/common_expand.dart';
import 'package:location/utils/http_handler.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../dialog/common_confirm_dialog_impl.dart';
import '../../../resource/string.gen.dart';
import '../../../utils/de_bounce.dart';
import '../../../utils/permission_util.dart';
import '../../../utils/toast_util.dart';

@injectable
class AddUrgentContactController extends BaseController {
  final RxString _contactPhone = RxString("");

  final TextEditingController etController = TextEditingController();

  String get contactPhone => _contactPhone.value;

  final Debounce _debounce = Debounce(debounceTime: 500);

  final UrgentContactRepository urgentContactRepository;
  final AccountRepository accountRepository;

  AddUrgentContactController(
      this.urgentContactRepository, this.accountRepository);

  @override
  void onReady() {
    etController.addListener(() {
      _contactPhone.value = etController.text;
    });
  }

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

  void onSelectContactClick() async {
    bool isGranted = await PermissionUtil.checkPermission(Permission.contacts);
    if (!isGranted) {
      requestContactsPermissionDialog(onConfirm: () async {
        isGranted = await PermissionUtil.requestPermission(Permission.contacts);
        if (isGranted) {
          _goContact();
        } else {
          ToastUtil.show(StringName.permissionRequestFail);
        }
      });
    } else {
      _goContact();
    }
  }

  void _goContact() async {
    final contact = await FlutterContacts.openExternalPick();
    if (contact != null) {
      final phones = contact.phones;
      if (phones.isNotEmpty) {
        etController.text = phones.first.number.trimAll();
      }
    }
  }

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

  void onAddClick() {
    if (contactPhone.length < 11) {
      return;
    }
    if(contactPhone == accountRepository.loginPhoneNum.value) {
      ToastUtil.show(StringName.urgentContactAddSelf);
      return;
    }
    _debounce.onClick(() {
      if (accountRepository.memberIsExpired()) {
        MemberPage.start();
        return;
      }
      urgentContactRepository.addContact(contactPhone).then((_) {
        ToastUtil.show(StringName.urgentContactAddSuccess);
        Get.back(result: true);
      }).catchError((e) {
        if (e is ServerErrorException) {
          if (e.code == ErrorCode.contactAlreadyAdded) {
            ToastUtil.show(StringName.urgentContactHasBeenAdded);
          } else {
            ErrorHandler.toastError(e);
          }
        } else {
          ErrorHandler.toastError(e);
        }
      });
    });
  }
}
