#include "frontend/app/components/trace_viewer_v2/color/color_generator.h"

#include <optional>
#include <vector>

#include "absl/log/check.h"
#include "absl/types/span.h"
#include "frontend/app/components/trace_viewer_v2/color/colors.h"
#include "absl/base/no_destructor.h"
#include "tsl/platform/fingerprint.h"
#include "absl/strings/string_view.h"
#include "imgui.h"

namespace traceviewer {

namespace {

// Generates colors based on string IDs.
// The color is generated by hashing the ID and picking a color from a
// predefined list.
class ColorGenerator {
 public:
  ColorGenerator(const ColorGenerator&) = delete;
  ColorGenerator& operator=(const ColorGenerator&) = delete;
  ColorGenerator(ColorGenerator&&) = delete;
  ColorGenerator& operator=(ColorGenerator&&) = delete;

  // Returns a color for the given ID.
  ImU32 ColorForId(absl::string_view id, absl::Span<const ImU32> event_colors) {
    return event_colors[tsl::Fingerprint64(id) %
                        event_colors.size()];
  }

 private:
  friend class absl::NoDestructor<ColorGenerator>;
  ColorGenerator() = default;
};

}  // namespace

// Generates a color for a given string ID.
// The color is generated by hashing the ID and picking a color from a
// predefined list.
ImU32 GetColorForId(absl::string_view id,
                    absl::Span<const ImU32> event_colors) {
  static absl::NoDestructor<ColorGenerator> generator;
  CHECK(!event_colors.empty());
  return generator->ColorForId(id, event_colors);
}

}  // namespace traceviewer
