import 'package:connectivity/connectivity.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/models/doctor/list_doctor_working_hours_table_model.dart';
import 'package:doctor_app_flutter/screens/auth/login_screen.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:html/parser.dart';

import '../UpdatePage.dart';
import '../config/size_config.dart';
import '../util/dr_app_toast_msg.dart';
import 'dr_app_shared_pref.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
class Helpers {
  static int cupertinoPickerIndex = 0;

  get currentLanguage => null;
  static showCupertinoPicker(context, items, decKey, onSelectFun) {
    showModalBottomSheet(
        isDismissible: false,
        context: context,
        builder: (BuildContext builder) {
          return Container(
            // height: 500,
            height: SizeConfig.realScreenHeight * 0.4,
            color: Color(0xfff7f7f7),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                  color: Color(0xfff7f7f7),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      CupertinoButton(
                        child: Text(TranslationBase.of(context).cancel,
                            style: textStyle(context)),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      CupertinoButton(
                        child: Text(
                          TranslationBase.of(context).done,
                          style: textStyle(context),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                          onSelectFun(cupertinoPickerIndex);
                        },
                      )
                    ],
                  ),
                ),
                Container(
                    height: SizeConfig.realScreenHeight * 0.3,
                    color: Color(0xfff7f7f7),
                    child:
                        buildPickerItems(context, items, decKey, onSelectFun))
              ],
            ),
          );
        });
  }

  static TextStyle textStyle(context) =>
      TextStyle(color: Theme.of(context).primaryColor);

  static buildPickerItems(context, List items, decKey, onSelectFun) {
    return CupertinoPicker(
      magnification: 1.5,
      scrollController:
          FixedExtentScrollController(initialItem: cupertinoPickerIndex),
      children: items.map((item) {
        return Text(
          '${item["$decKey"]}',
          style: TextStyle(fontSize: SizeConfig.textMultiplier * 2),
        );
      }).toList(),

      itemExtent: 25,
      looping: false,
      onSelectedItemChanged: (int index) {
        cupertinoPickerIndex = index;
      },
    );
  }

  static showErrorToast([msg = null]) {
    String localMsg = generateContactAdminMsg();

    if (msg != null) {
      localMsg = msg.toString();
    }

    DrAppToastMsg.showErrorToast(localMsg);
  }
  static Future<bool> checkConnection() async {
    ConnectivityResult connectivityResult =
        await (Connectivity().checkConnectivity());
    if ((connectivityResult == ConnectivityResult.mobile) ||
        (connectivityResult == ConnectivityResult.wifi)) {
      return true;
    } else {
      return false;
    }
  }

  static List<WorkingHours> getWorkingHours(String workingHours) {
    List<WorkingHours> myWorkingHours = [];
    List<String> listOfHours = workingHours.split('a');

    listOfHours.forEach((element) {
      WorkingHours workingHours = WorkingHours();
      var from = element.substring(
          element.indexOf('m ') + 2, element.indexOf('To') - 1);
      workingHours.from = from.trim();
      var to = element.substring(element.indexOf('To') + 2);
      workingHours.to = to.trim();
      myWorkingHours.add(workingHours);
    });
    return myWorkingHours;
  }

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

  static clearSharedPref() async {
    await sharedPref.clear();
  }

  static logout() async {
    DEVICE_TOKEN = "";
    String lang = await sharedPref.getString(APP_Language);
    await clearSharedPref();
    sharedPref.setString(APP_Language, lang);
    Navigator.pushAndRemoveUntil(AppGlobal.CONTEX, FadePage(page: Loginsreen(),), (r) => false);

  }

  navigateToUpdatePage(String message, String androidLink, iosLink) {
    Navigator.pushAndRemoveUntil(
        AppGlobal.CONTEX,
        FadePage(
          page: UpdatePage(
            message: message,
            androidLink: androidLink,
            iosLink: iosLink,
          ),
        ),
            (r) => false);
  }

  static String parseHtmlString(String htmlString) {
    final document = parse(htmlString);
    final String parsedString = parse(document.body.text).documentElement.text;

    return parsedString;
  }

  static InputDecoration textFieldSelectorDecoration(
      String hintText, String selectedText, bool isDropDown,
      {Icon suffixIcon, Color dropDownColor}) {
    return InputDecoration(
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown
          ? suffixIcon != null
              ? suffixIcon
              : Icon(
                  Icons.arrow_drop_down,
                  color: dropDownColor != null ? dropDownColor : Colors.black,
                )
          : null,
      hintStyle: TextStyle(
        fontSize: 14,
        color: Colors.grey.shade600,
      ),
    );
  }

  static BoxDecoration containerBorderDecoration(
      Color containerColor, Color borderColor,
      {double borderWidth = -1}) {
    return BoxDecoration(
      color: containerColor,
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(8)),
      border: Border.fromBorderSide(BorderSide(
        color: borderColor,
        width: borderWidth == -1 ? 2.0 : borderWidth,
      )),
    );
  }

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

  static String capitalize(str) {
    if (str != "") {
      return "${str[0].toUpperCase()}${str.substring(1).toLowerCase()}";
    } else {
      return str;
    }
  }
}
