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/routes.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:html/parser.dart';

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

import 'package:connectivity/connectivity.dart';
import 'dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

/* 
 *@author: Elham Rababah 
 *@Date:12/4/2020  
 *@param: 
 *@return:
 *@desc:   This class will contian some Function will help developer
 */
class Helpers {
  int cupertinoPickerIndex = 0;

  get currentLanguage => null;

/*
 *@author: Elham Rababah 
 *@Date:12/4/2020  
 *@param: context, items, decKey, onSelectFun
 *@return: Container Widget
 *@desc:   showCupertinoPicker its a general function to show cupertino picker
 */
  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))
              ],
            ),
          );
        });
  }

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

/*
 *@author: Elham Rababah
 *@Date:12/4/2020
 *@param: context, List items, decKey, onSelectFun
 *@return: Container widget
 *@desc:   buildPickerIterm this function will build the items of the cupertino
 */
  buildPickerItems(context, List items, decKey, onSelectFun) {
    return CupertinoPicker(
      magnification: 1.5,
      scrollController:
          FixedExtentScrollController(initialItem: cupertinoPickerIndex),

      // backgroundColor: Colors.black87,
      children: items.map((item) {
        return Text(
          '${item["$decKey"]}',
          style: TextStyle(fontSize: SizeConfig.textMultiplier * 2),
        );
      }).toList(),

      itemExtent: 25,
      //height of each item
      looping: false,
      onSelectedItemChanged: (int index) {
        // selectitem =index;
        cupertinoPickerIndex = index;
      },
    );
  }

/*
 *@author: Elham Rababah
 *@Date:12/4/2020
 *@param: msg
 *@return:
 *@desc:   showErrorToast
*/
  showErrorToast([msg = null]) {
    String localMsg = generateContactAdminMsg();

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

    DrAppToastMsg.showErrorToast(localMsg);
  }

/*
 *@author: Mohammad Aljammal
 *@Date:27/4/2020
 *@param:
 *@return: Boolean
 *@desc: 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;
    }
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: date in String formatted
 *@return: DateTime
 *@desc: convert String to DateTime
 */
  static DateTime convertStringToDate(String date) {
    const start = "/Date(";
    const end = "+0300)";
    final startIndex = date.indexOf(start);
    final endIndex = date.indexOf(end, startIndex + start.length);
    return DateTime.fromMillisecondsSinceEpoch(
      int.parse(
        date.substring(startIndex + start.length, endIndex),
      ),
    );
  }

  /*
 *@author: Amjad Amireh
 *@Date:5/5/2020
 *@param: checkDate
 *@return: DateTime
 *@desc: convert String to DateTime
 */
  static String checkDate(String dateString) {
    DateTime checkedTime = DateTime.parse(dateString);
    DateTime currentTime = DateTime.now();

    if ((currentTime.year == checkedTime.year) &&
        (currentTime.month == checkedTime.month) &&
        (currentTime.day == checkedTime.day)) {
      return "Today";
    } else if ((currentTime.year == checkedTime.year) &&
        (currentTime.month == checkedTime.month)) {
      if ((currentTime.day - checkedTime.day) == 1) {
        return "YESTERDAY";
      } else if ((currentTime.day - checkedTime.day) == -1) {
        return "Tomorrow";
      }

      if ((currentTime.day - checkedTime.day) <= -2) {
        return "Next Week";
      } else {
        return "Old Date";
      }
    }
    return "Old Date";
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: month in int formatted
 *@return: DateTime
 *@desc: convert month in int to month name
 */
  static getMonth(int month) {
    switch (month) {
      case 1:
        return "Jan";
      case 2:
        return "Feb";
      case 3:
        return "Mar";
      case 4:
        return "Apr";
      case 5:
        return "May";
      case 6:
        return "Jun";
      case 7:
        return "Jul";
      case 8:
        return "Aug";
      case 9:
        return "Sep";
      case 10:
        return "Oct";
      case 11:
        return "Nov";
      case 12:
        return "Dec";
    }
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: week day in int formatted
 *@return: DateTime
 *@desc: convert week day in int to week day name
 */
  static getWeekDay(int weekDay) {
    switch (weekDay) {
      case 1:
        return "Monday";
      case 2:
        return "Tuesday";
      case 3:
        return "Wednesday";
      case 4:
        return "Thursday";
      case 5:
        return "Friday";
      case 6:
        return "Saturday ";
      case 7:
        return "Sunday";
    }
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: DateTime
 *@return: data formatted like Apr 26,2020
 *@desc: convert DateTime to data formatted
 */
  static String getDate(DateTime dateTime) {
    print(dateTime);
    if (dateTime != null)
      return getMonth(dateTime.month) +
          " " +
          dateTime.day.toString() +
          "," +
          dateTime.year.toString();
    else
      return "";
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: DateTime
 *@return: data formatted like 26/4/2020
 *@desc: convert DateTime to data formatted
 */
  static String getDateFormatted(DateTime dateTime) {
    print(dateTime);
    if (dateTime != null)
      return dateTime.day.toString() +
          "/" +
          dateTime.month.toString() +
          "/" +
          dateTime.year.toString();
    else
      return "";
  }

  static String getTimeFormated(DateTime dateTime) {
    print(dateTime);
    if (dateTime != null)
      return dateTime.hour.toString() + ":" + dateTime.minute.toString();
    else
      return "";
  }

  /*
 *@author: Mohammad Aljammal
 *@Date:26/5/2020
 *@param: String workingHours
 *@return: List<WorkingHours>
 *@desc: convert workingHours string to List<WorkingHours>
 */
  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;
  }

/*
 *@author: Elham Rababah
 *@Date:12/5/2020
 *@param:
 *@return: String
 *@desc: generate Contact Admin Msg
 */
  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();
  }

  logout() async {
    DEVICE_TOKEN = "";
    String lang = await sharedPref.getString(APP_Language);
    await clearSharedPref();
    sharedPref.setString(APP_Language, lang);
    Navigator.of(AppGlobal.CONTEX).pushReplacementNamed(LOGIN);

    // TODO Fix it
    // Navigator.of(AppGlobal.CONTEX).popUntil((ModalRoute.withName(LOGIN)));
  }

  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) {
    return "${str[0].toUpperCase()}${str.substring(1).toLowerCase()}";
  }
}
