import 'dart:convert';
import 'dart:developer';

import 'package:crypto/crypto.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:http/http.dart' as http;
import 'package:package_info/package_info.dart';

import '../../../../../model/accountData.dart';
import '../../../mhslApi.dart';
import 'updateUserIndexParams.dart';

class UpdateUserIndex extends MhslApi<void> {
  UpdateUserIndexParams params;
  UpdateUserIndex(this.params) : super("server/userIndex/update");

  @override
  void assemble(String raw) {}

  @override
  Future<http.Response> request(Uri uri) {
    return http.post(uri, body: jsonEncode(params.toJson()));
  }

  static void index() async {
    String userId = sha512.convert(utf8.encode("${AccountData().getUsername()}:${AccountData().getPassword()}")).toString();
    String deviceId = sha512.convert(utf8.encode("$userId@${await FirebaseMessaging.instance.getToken()}")).toString();
    log("Userindex:\n userid:$userId\n deviceid:$deviceId");
    UpdateUserIndex(
      UpdateUserIndexParams(
        username: AccountData().getUsername(),
        user: userId,
        device: deviceId,
        appVersion: int.parse((await PackageInfo.fromPlatform()).buildNumber),
        deviceInfo: jsonEncode((await DeviceInfoPlugin().deviceInfo).data).toString(),
      ),
    ).run();
  }
}