import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'app_shared_preferences.dart';
import 'app_toast.dart';

AppSharedPreferences sharedPref = new AppSharedPreferences();

class Utils {

  ///show  custom Error Toast
  ///  [message] to show for user
  static showErrorToast([String message]) {
    String localMsg = generateContactAdminMessage();
    if (message != null) {
      localMsg = message.toString();
    }
    AppToast.showErrorToast(message: localMsg);
  }

  /// Check The Internet Connection
  static Future<bool> checkConnection() async {
    ConnectivityResult connectivityResult =
        await (Connectivity().checkConnectivity());
    if ((connectivityResult == ConnectivityResult.mobile) ||
        (connectivityResult == ConnectivityResult.wifi)) {
      return true;
    } else {
      return false;
    }
  }

  /// generate Contact Admin Message
  static generateContactAdminMessage([err]) {
    String localMsg = 'Something wrong happened, please contact the admin';
    if (err != null) {
      localMsg = localMsg + '\n \n' + err.toString();
    }
    return localMsg;
  }

  /// hides the keyboard if its already open
  static hideKeyboard(BuildContext context) {
    FocusScope.of(context).unfocus();
  }

  bool isSAUDIIDValid(String id, type) {
    if (type == 1) {
      if (id == null) {
        return false;
      }
      try {
        id = id.toString();
        id = id.trim();
        var returnValue = int.parse(id);
        var sum = 0;
        if (returnValue > 0) {
          var type = int.parse(id[0]);

          if (id.length != 10) {
            return false;
          }
          if (type != 2 && type != 1) {
            return false;
          }

          for (var i = 0; i < 10; i++) {
            if (i % 2 == 0) {
              var a = id[i];
              var x = int.parse(a) * 2;
              var b = x.toString();
              if (b.length == 1) {
                b = "0" + b;
              }
              sum += int.parse(b[0]) + int.parse(b[1]);
            } else {
              sum += int.parse(id[i]);
            }
          }
          return sum % 10 == 0;
        }
      } catch (err) {}
      return false;
    } else {
      return true;
    }
  }

  static String getAppointmentTransID(int projectID, int clinicID, int appoNo) {
    return projectID.toString() +
        '-' +
        clinicID.toString() +
        '-' +
        appoNo.toString();
  }

  bool validateIDBox(String value, type) {
    Pattern pattern = loginIDPattern(type); //r'^\d+(?:\.\d+)?$';

    RegExp regex = new RegExp(pattern);
    return regex.hasMatch(value);
  }

  String loginIDPattern(loginType) {
    var length = loginType == 1 ? 10 : 7;
    return "([0-9]{" + length.toString() + "})";
  }
}
