import 'dart:async';
import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:imei_plugin/imei_plugin.dart';
import 'package:meta/meta.dart';
import 'package:peasmartcare/models/otp_model.dart';
import 'package:peasmartcare/models/register_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/services/authen_service.dart';
import 'package:peasmartcare/utils/firestore_log.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:uuid/uuid.dart';

part 'register_event.dart';
part 'register_state.dart';

class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
  AuthenImpService service = AuthenImpService();
  FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  String osName;
  String osVersion;
  String deviceModel;

  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  Map<String, dynamic> _deviceData = <String, dynamic>{};

  RegisterBloc() : super(RegisterInitial());

  @override
  Stream<RegisterState> mapEventToState(RegisterEvent event) async* {
    try {
      if (event is RegisterOnSubmit) {
        yield RegisterLoading();
        ShareDataUtil.clear();
        await initPlatformState();
        String firstname = event.firstname;
        String lastname = event.lastname;
        String idCard = event.idCard;
        String phone = event.phone;
        int cardTypeId = event.cardTypeId;
        var uuidImei = Uuid();
        // String imei = uuidImei.v5(Uuid.NAMESPACE_URL, 'www.pea.co.th'); //
        String imei;
        try {
          imei = await ImeiPlugin.getImei(
              shouldShowRequestPermissionRationale: false);
        } on PlatformException {
          imei = 'Perrmission Denied';
        }

        var uuid = Uuid();
        String deviceId = uuid.v5(Uuid.NAMESPACE_URL, 'www.pea.co.th');
        String firebaseToken = await firebaseMessaging.getToken();

        ResultData resultData = await service.register(
          firstname: firstname,
          lastname: lastname,
          idCard: idCard,
          phone: phone,
          cardTypeId: cardTypeId,
          osName: osName,
          osVersion: osVersion,
          imei: imei,
          deviceId: deviceId,
          firebaseToken: firebaseToken,
          deviceModel: deviceModel,
        );

        print("Register ${resultData.statusMessage}");
        print("Register ${resultData}");

        RegisterModel register = resultData.result;
        print("RegisterModel ${register.authenKey}");
        print("RegisterModel ${register.message}");
        print("RegisterModel ${register.firstname}");
        print("RegisterModel ${register.id}");
        print("RegisterModel ${register.idCard}");
        print("RegisterModel ${register.isSuccess}");
        print("RegisterModel ${register.lastname}");
        print("RegisterModel ${register.phone}");
        print("RegisterModel ${register}");

        if (register != null && register.isSuccess) {
          ResultData resultOTPData = await service.sendOTP(
            phoneNumber: phone,
            message: "**pw**",
            authenKey: register.authenKey,
          );

          ShareDataUtil.setAuthenKey(register.authenKey);
          ShareDataUtil.setFirebaseToken(firebaseToken);

          UserModel user = UserModel();
          user.id = register.id;
          user.firstname = register.firstname;
          user.lastname = register.lastname;
          user.idCard = register.idCard;
          user.phone = register.phone;

          ShareDataUtil.setUserInfo(user);

          await FirestoreLog.log(
            fullname: "${user.firstname} ${user.lastname}",
            authenKey: ShareDataUtil.getAuthenKey(),
            activity: "Register",
          );

          if (resultOTPData.result != null) {
            yield RegisterLoaded(result: true, otpResult: resultOTPData.result);
          } else {
            yield RegisterLoaded(result: false);
          }
        } else if (register != null && !register.isSuccess) {
          yield RegisterError(message: register.message);
        } else {
          yield RegisterLoaded(result: false);
        }
      }
    } catch (e) {
      print("catch  Register ${e}");

      yield RegisterError(message: "เกิดข้อผิดพลาด");
    }
  }

  Future<void> initPlatformState() async {
    if (Platform.isAndroid) {
      _deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
    } else if (Platform.isIOS) {
      _deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
    }
  }

  Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    osName = "Android";
    osVersion = build.version.release;
    deviceModel = build.brand;

    return <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'androidId': build.androidId,
      'systemFeatures': build.systemFeatures,
    };
  }

  Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    osName = "iOS";
    osVersion = data.systemVersion;
    deviceModel = data.name;
    return <String, dynamic>{
      'name': data.name,
      'systemName': data.systemName,
      'systemVersion': data.systemVersion,
      'model': data.model,
      'localizedModel': data.localizedModel,
      'identifierForVendor': data.identifierForVendor,
      'isPhysicalDevice': data.isPhysicalDevice,
      'utsname.sysname:': data.utsname.sysname,
      'utsname.nodename:': data.utsname.nodename,
      'utsname.release:': data.utsname.release,
      'utsname.version:': data.utsname.version,
      'utsname.machine:': data.utsname.machine,
    };
  }
}
