import 'package:flutter/material.dart';

/// Created by Haoyi on 4/28/21

class ColorUtils {
  static Color toColor(String? colorStr, {Color defaultColor = Colors.white}) {
    if (colorStr == null) {
      return defaultColor;
    }
    String colorValue = colorStr.toUpperCase().replaceAll("#", "");
    int value = int.parse(colorValue, radix: 16);
    if (colorValue.length == 3) {
      return Color.fromARGB(
          0xFF,
          ((((value >> 8) & 0x0F) / 0x0F) * 0xFF).toInt(),
          ((((value >> 4) & 0x0F) / 0x0F) * 0xFF).toInt(),
          (((value & 0x0F) / 0x0F) * 0xFF).toInt());
    }
    if (colorValue.length == 6) {
      value = value | 0xFF000000;
    }

    return Color(value);
  }


  static final _ASCII_A = "A".codeUnitAt(0);
  static final _ASCII_0 = "0".codeUnitAt(0);
  static final _ASCII_9 = "9".codeUnitAt(0);
  static final _ASCII_DOT = ".".codeUnitAt(0);

  static int toColorValue(String colorStr, {Color defaultColor = Colors.white}) {
    if (colorStr == null) {
      return defaultColor.value;
    }
    String colorValue = colorStr.toUpperCase().replaceAll("#", "");
    if (colorValue.length == 3) {
      return Color.fromARGB(
          0xFF,
          (((colorValue[0].codeUnitAt(0) - _ASCII_A) / 0x0F) * 0xFF).toInt(),
          (((colorValue[1].codeUnitAt(0) - _ASCII_A) / 0x0F) * 0xFF).toInt(),
          (((colorValue[2].codeUnitAt(0) - _ASCII_A) / 0x0F) * 0xFF).toInt())
          .value;
    }
    if (colorValue.length == 6) {
      colorValue = "FF" + colorValue;
    }

    return int.parse(colorValue, radix: 16);
  }
}
