import 'dart:typed_data';

import 'package:bip32/bip32.dart' as bip32;
import 'package:bip39_multi_language/bip39.dart' as bip39;
import 'package:chat/utils/ui_tools.dart';
import 'package:fast_base58/fast_base58.dart';
import 'package:hash/hash.dart';

class HDWallet {
  /// 将助记词转换成BTY地址
  static String? mnemonicToAddress(String mnemonic) {
    var li = mnemonic.split(' ');
    li.removeWhere((e) => e.isEmpty);
    mnemonic = li.join(' ');

    if (!bip39.validateMnemonic(
      mnemonic,
      language: _languageDetect('mnemonic'),
    )) {
      UiTools.toast('不符合标准的助记词');
      return null;
    }

    var seed = bip39.mnemonicToSeed(mnemonic);
    var root = bip32.BIP32.fromSeed(seed);
    var child = root.derivePath("m/44'/13107'/0'/0/0");
    var step3 = SHA256().update(child.publicKey).digest();
    List<int> step4 = List.from(RIPEMD160().update(step3).digest());
    step4.insert(0, 0x00);
    List<int> step5 = step4;
    Uint8List step6 = SHA256().update(step5).digest();
    Uint8List step7 = SHA256().update(step6).digest();
    step5.addAll(step7.sublist(0, 4));
    Uint8List step8 = Uint8List.fromList(step5);

    return Base58Encode(step8);
  }

  /// 判断是否是英文助记词
  static String _languageDetect(String str) {
    if (str.startsWith(RegExp(r'[a-z]'))) {
      return 'english';
    } else {
      return 'chinese';
    }
  }
}
