// ignore_for_file: unnecessary_null_comparison

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:http/http.dart' as http;
import '../main.dart';
import 'logger.dart';

//** START FUNCTION */
String separatorThousand = ','; // pemisah ribuan
NumberFormat formatNumber() {
  if (separatorThousand == ',') {
    return NumberFormat('#,###');
  } else if (separatorThousand == '.') {
    return NumberFormat.currency(locale: 'id', symbol: '', decimalDigits: 0);
  } else {
    return NumberFormat('#,###');
  }
}

//** untuk parsing String dari API yang harusnya int */
int amountParseToInt(String amount) {
  // return int.parse(amount.split('.00')[0]);
  return int.parse(amount.split('.')[0]);
}

int amountParseToIntCrm(String amount) {
  var x = amount.split(',');
  var stringAfterSplit = x.join();
  return int.parse(stringAfterSplit);
}
//** untuk parsing String dari API yang harusnya int */

//** httpPostLoger */
Future<dynamic> httpPost(
    String apiUrl, String bodies, String namaFungsi) async {
  var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
  if (apiResult.statusCode == 200 || apiResult.statusCode == 401) {
    // 401 dilolosin karena mau nangkep message dari backend > show to user
    var jsonObject = jsonDecode(apiResult.body);
    return jsonObject;
  } else {
    if (debug) {
      logd('API CLASS ON API.DART, FUNGSI: $namaFungsi, URL : $apiUrl',
          'ERROR CONNECT TO SERVER, RESPONSE CODE : ${apiResult.statusCode}');
    }
    return false;
  }
}

Future<dynamic> sendTele(String teks, String namaFungsi) async {
  String tokenBot = '5582109697:AAH3L_5fl8tZ6qRhNeTR8lHdXbO4hrt2WzE';
  String groupID = '-670190632';
  await http.get(
    Uri.parse(
        'https://api.telegram.org/bot$tokenBot/sendMessage?chat_id=$groupID&text=$teks'),
  );
  return true;
}
//** httpPostLoger */

//**get orderStatus */
String getOrderStatus(int status) {
  if (status == completeOrder) {
    return 'Complete';
  } else if (status == cancelOrder) {
    return 'Canceld';
  } else if (status == processingOrder) {
    return 'Preparing';
  } else {
    return 'Pending';
  }
}
//**get orderStatus */

//**get payment Status */
String getpaymentStatus(bool isApproved, int method) {
  if (isApproved) {
    if (method == payVoucher) {
      return 'Voucher';
    } else {
      return 'Lunas';
    }
  } else {
    if (method == payCash) {
      return 'Selesaikan di kasir';
    } else {
      return 'Belum Selesai';
    }
  }
}
//**get payment Status */

//**get payment Status Color */
Color getPaymentStatusColor(bool isApproved) {
  if (isApproved) {
    return successColor;
  } else {
    return pendingColor;
  }
}
//**get payment Status Color */

//** for Responsive layout */
double responsiveWidthScreen(context) {
  double widhtScreen = MediaQuery.of(context).size.width;
  double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
  if (widhtScreen > maxWidthScreen) {
    return maxWidthScreen;
  } else {
    return widhtScreen;
  }
}

double getMaxWidthScreen(context, bool useResponsive) {
  double widhtScreen = MediaQuery.of(context).size.width;
  if (useResponsive) {
    return maxWidthScreens;
  } else {
    return widhtScreen;
  }
}

double responsiveHeigthScreen(context) {
  double heigthScreen = MediaQuery.of(context).size.height;
  if (heigthScreen > maxHeightScreens) {
    return maxHeightScreens;
  } else {
    return heigthScreen;
  }
}

double ratioWidthHeigth(context) {
  double heigthScreen = MediaQuery.of(context).size.height;
  double widthScreen = responsiveWidthScreen(context);
  double ratio = heigthScreen / widthScreen;
  return ratio;
}
//** for Responsive layout */

//** convert UTC to local */

String formatDate(String timeString, {toLocal = false}) {
  final dateTimeParse = DateTime.tryParse(timeString);
  String dateResult;
  if (dateTimeParse != null) {
    DateTime dateTime;
    if (toLocal) {
      dateTime = DateTime.parse(timeString).toLocal();
    } else {
      dateTime = DateTime.parse(timeString);
    }

    final formatDate = DateFormat('dd-MM-yyy').format(dateTime).toString();
    dateResult = localDate(formatDate);
  } else {
    dateResult = timeString;
  }

  // DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm:ss").parse(timeString);
  // var dateLocal = tempDate.toLocal();
  return dateResult;
}

String localDate(String date, {isHistory = false}) {
  String day;
  String year;
  if (!isHistory) {
    year = date.split('-')[2];
    day = date.split('-')[0];
  } else {
    year = date.split('-')[0];
    day = date.split('-')[1];
  }

  String month = date.split('-')[1];
  String resultMonth = '';
  switch (month) {
    case "01":
      {
        resultMonth = "Januari";
      }
      break;
    case "02":
      {
        resultMonth = "Februari";
      }
      break;
    case "03":
      {
        resultMonth = "Maret";
      }
      break;
    case "04":
      {
        resultMonth = "April";
      }
      break;
    case "05":
      {
        resultMonth = "Mei";
      }
      break;
    case "06":
      {
        resultMonth = "Juni";
      }
      break;
    case "07":
      {
        resultMonth = "Juli";
      }
      break;
    case "08":
      {
        resultMonth = "Agustus";
      }
      break;
    case "09":
      {
        resultMonth = "September";
      }
      break;
    case "10":
      {
        resultMonth = "Oktober";
      }
      break;
    case "11":
      {
        resultMonth = "November";
      }
      break;
    case "12":
      {
        resultMonth = "Desember";
      }
      break;
  }
  return "$day-$resultMonth-$year";
}

//** convert UTC to local */

//** END FUNCTION */

//** START CONSTANT */

//**Height tombol */
double heightTombol = 0.06; // untuk dikalikan di height media query
//**Height tombol */

//** kalkulasi pixel dihome */
String logoUrl = prefs.getString("logoUrl") ?? "";

double imageHeight = (logoUrl != '') ? 96 : 0;
double heighScrollWithImage = 371 + imageHeight;
double heighScrollWithOutImage = 371;
//** */

//** core warna */
// const Color backgroundColor = Colors.white;
const Color backgroundColor = Color(0xffF4F4F4);
const Color backgroundColorViewBill = Color(0xffE5E5E5);
const Color backgroundWhite = Color(0xffFFFFFF);
const Color dividerGrey = Color(0xff898A8D);
const Color greyColor = Color(0xffD9D9D9);
const textColorTabel = Color(0xff333333);
const textColorBlack = Color(0xff000000);
const textColorRed = Color(0xffE73636);
const textColorPlaceHolder = Color(0xffA89C9C);
const textGrey = Color(0xffE0E0E0);
const textGreyBill = Color(0xff828282);
const textGreyDeskripsi = Color(0xffBDBDBD);
const backgroundColorBottomSheet = Color(0xffE5E5E5);
const textColorModalHeaderNama = Color(0xff50555C);
const gridCardBackgroundColor = Color(0xffFFFFFF);
Color buttonColor =
    (!isExcelso) ? const Color(0xff003366) : const Color(0xffccb46c);
Color dangerColor = Colors.red.withOpacity(0.9);
Color cancelColorButton = Colors.transparent;
const Color textInButton = Colors.white;
const Color textCancelColor = Color(0xff333333);
const Color successColor = Colors.green;
const Color processingColor = Colors.blue;
const Color pendingColor = Colors.amber;
const Color disabledColor = Colors.grey;
// const Color selectedColor = Color.fromARGB(255, 225, 250, 5);
Color selectedColor = (!isExcelso) ? Colors.green : const Color(0xff047383);
Color? backGroundPayment = Colors.grey[200] ?? Colors.grey;
Color responsiveLeftRigth = buttonColor;

const Color baseColorShimmer = Colors.grey;
const Color highlightColorShimmer = Color.fromARGB(255, 226, 225, 225);
//** core warna */

//** URLs API */
// const String baseUrl = 'https://romi.cs.co.id/romi/api/byod/';
// const String crmUrl = 'https://excelso.ravintolavip.com/crm/v1/';
//** URLs API */

//** untuk type variant */
const int typeMandatory = 0;
const int typeOptional = 1;
const int typeAutoInsert = 2;
//** untuk type variant */

//** untuk status payment */
const int waitingPayment = 99;
const int successPayment = 2;
const int processingPayment = 1;
const int unpaidPayment = 0;
//** untuk status payment */

//** untuk menentukan bayar pakai apa */
const int payCash = 0;
const int payCard = 1;
const int payCashCard = 2;
const int paySigned = 3;
const int payVoucher = 4;
const int payCustomVoucher = 5;
const int payEntertaintment = 6;
const int payDownPayment = 7;
const int payOnline = 8;
const int payTransfer = 9;
//** untuk menentukan bayar pakai apa */

//** untuk API addpayment */
const int partialPayment = 0;
const int fullPayment = 1;
//** untuk API addpayment */

//** untuk max panjang karakter textfield */
const int maxLengthTextField = 100;
//** untuk max panjang karakter textfield */

//** untuk nampilin orderan preparing atau compelete */
const int cancelOrder = -1;
const int completeOrder = 2;
const int pendingOrder = 0;
const int processingOrder = 1;
//** untuk nampilin orderan preparing atau compelete */

//** untuk cek status table orderan */
const int tableStatusOpen = 0;
const int tableStatusSoftLock = 1;
const int tableStatusHardtLock = 2;
const int tableStatusClose = 4;
//** untuk cek status table orderan */

//** untuk response API getbranch */
const String responseApiNoSuccess = 'not_success';
const String responseApiErrorServer = 'error_server';
const String responseApiWaiting = 'waiting';
const String responseByodInActive = 'inactive';
const String responseByodBranchExist = 'branchExist';
//** untuk response API getbranch */

//** TABLE MODE */
const int singleTable = 1;
const int multiTable = 2;
const int defaultTable = 2; // default table di multiin aja
//** TABLE MODE */

//** DURATION ANIMATED SWITECHER in ms */
int animatedTime = 200;
//** DURATION ANIMATED SWITECHER */

//** KEY Untuk Storage Secure */
// const String tableKey = 'tabel';
//** KEY Untuk Storage Secure */

//**Ukuran Font Via Media Query */
const double categoryFont = 0.035;
const double listHistoryFontName = 0.02;
const double listOrderFontOther = 0.018;
const double groupFont = 0.03;
const double menuFont = 0.025;
const double descriptionFont = 0.017;
const double voucherListFont = 0.02;
const double summaryFont = 0.022;
const double normalFont = 0.02;
const double addButtonFont = 0.02;
const double variantModalFont = 0.015;
const double refreshFont = 0.013;
const double addMoreFont = 0.018;
const double versionFont = 0.013;
const double moreValueVoucher = 0.013;
const double minTransFont = 0.015;
const double rateFont = 0.015;
const double categoryListFont = 0.017;

const double textScaleFactor = 1.0;
//**Ukuran Font Via Media Query */

//** Rounded Value */
double roundedButton = 10;
double roundedSmallButton = 5;
double roundedImage = 20;
double roundedDetailPayment = 10;
//** Rounded Value */

//** Show Dialog Width */
double widhtDialog = 0.7;
double countRateEmot = 3;
double widthEmoticon = 0.18;
double heightEmoticon = 0.18;
//** Show Dialog Width */

//** string untuk default viewbill */
String defaultViewBill = 'default';
//** string untuk default viewbill */

//** call from untuk notemenu */
String fromMenu = 'menu';
String fromBill = 'bill';
//** call from untuk notemenu */

//**Rating Value */
const int badRate = 1;
const int neutralRate = 2;
const int goodRate = 3;
const int defaultRate = goodRate;
const int noRate = -2;
//**Rating Value */

//** Place holder */
String placeHolderNote = 'Catatan pesanan';
//** Place holder */

//** API penanda agregator for romi */
String fromByod = 'byod';
//** API penanda agregator for romi */

// ** button bottom config */
// akan di kali dengan media query
const heigthButtonBottom = 0.08;
// ** button bottom config */

//** padding bottom untuk button stack */
// akan dikalikan dengan media query height
const positionedBottom = 0.01;
//** padding bottom untuk button stack */

//** padding left right page */
const double paddingLeftRight = 20;
//** padding left right page */

//** Max widht screen */
bool useResponsive = isResponsive;
const double maxWidthScreens = 500;
const double maxHeightScreens = 600;
//** Max widht screen */

//** fontawesome unicode https://fontawesome.com/v5/cheatsheet/free/solid */

const String searchIcon = '\uf002';
const double searchIconSize = 0.03;

const String infoCircle = '\uf05a';
const double infoCircleSize = 0.015;

const String timesIcon = '\uf00d';
const double timesIconSize = 0.03;

const String timesCircleIcon = '\uf057';
const double timesCircleIconSize = 0.15;

const String checkCircleIcon = '\uf058';
const double checkCircleIconSize = 0.03;

const String listPesanan = '\uf022';
const double listPesananSize = 0.04;
const double listPesananSizeViewBill = 0.08;

const String shoppingCart = '\uf07a';

//** add remove menu */
const double addRemoveQuantityButtonSize = 0.025;

const String plusCicle = '\uf055';
const double plusCicleSize = addRemoveQuantityButtonSize;

const String minusCircle = '\uf056';
const double minusCircleSize = addRemoveQuantityButtonSize;

const String plusCicleNew = '\uf055';
const double plusCicleNewSize = 22;

const String minusCircleNew = '\uf056';
const double minusCircleNewSize = 22;

const String pencil = '\uf044';
const double pencilSize = 0.02;
//** add remove menu */

const String backIcon = '\uf060';
const double backIconSize = 0.03;

const String arrowBack = '\uf060';
const double arrowBackSize = 17;

const String arrowNext = '\uf105';
const double arrowNextSize = 14;

const String shopingBag = '\uf290';
const double shopingBagSize = 0.03;

const String refreshIcon = '\uf2f9';
const double refreshIconSize = 0.02;

//** fontawesome unicode */

//** max item menu */
const int maxItemMenu = 10;
const int maxItemMenuFav = 10;
//** max item menu */

//** type menu */
const int typeCategory = 1;
const int typeGroup = 2;
const int typeMenu = 3;
//** type menu */
//** END CONSTANT */
