import 'dart:async';

import 'package:aliyun_face_plugin/face_auth_plugins.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _infos = 'Unknown';
  final _aliyunFacePlugin = AliyunFacePlugin();

  @override
  void initState() {
    super.initState();

    // 在App启动的早期调用init接口。
    _aliyunFacePlugin.init();
  }

  Future<void> getMetaInfos() async {
    String metainfos;

    try {
      // 获取客户端metainfos，将信息发送到服务器端，调用服务器端相关接口获取认证ID，即CertifyId。
      metainfos = await _aliyunFacePlugin.getMetaInfos() ?? 'Unknown metainfos';
    } on PlatformException {
      metainfos = 'Failed to get metainfos.';
    }

    setState(() {
      _infos = "metainfos: " + metainfos;
    });
  }

  Future<void> startVerify() async {
    String verifyResult;
    try {
      // 调用认证接口，CertifyId需要调用服务器端接口获取。
      // 每个CertifyId只能使用一次，否则会返回code: "2002(iOS), 1001(Android)"。
      verifyResult = await _aliyunFacePlugin.verify({
            "certifyId": "shad04694918b4b774a74bc7e538fc67",
          }) ??
          '-1,error';
    } on PlatformException {
      verifyResult = '-2,exception';
    }

    setState(() {
      _infos = "verifyResult: " + verifyResult;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Aliyun face plugin demo')),
        body: Center(
            child: Column(children: <Widget>[
          Text('$_infos\n'),
          ElevatedButton(
              onPressed: () async {
                getMetaInfos();
              },
              child: Text("getMetaInfos")),
          ElevatedButton(
              onPressed: () async {
                startVerify();
              },
              child: Text("startVerify")),
        ])),
      ),
    );
  }
}
