/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2021 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

#include <functional>
#include "mpmo_color.h"

bool stdin_is_tty = false;
bool stdout_is_tty = false;
bool stderr_is_tty = false;
int colorBehaviour = Auto;
bool
color_enabled()
{
  if (colorBehaviour == Auto)
    {
      if (stderr_is_tty && stdout_is_tty) return true;
    }
  if (colorBehaviour == All) return true;
  if (colorBehaviour == No) return false;
  return false;
}

void
mpmo_color_set(int p_colorBehaviour)
{
  colorBehaviour = p_colorBehaviour;
}

int
mpmo_get_color_mode()
{
  return colorBehaviour;
}

int CDO_Color = 1;

void
set_text_color(FILE *fp, TextMode attr, TextColor fg)
{
  if (!color_enabled()) return;
  if (!color_enabled()) return;

  // fprintf(fp, "%c[%d", 0x1B, attr);
  // if (fg >= 0)
  //  {
  //    fprintf(fp, ";%d", fg + 30);
  //    if (bg >= 0) fprintf(fp, ";%d", bg + 40);
  //  }
  //
  std::string color_str = color(fg, attr, NO_COLOR);
  fprintf(fp, "%s", color_str.c_str());
}

void
set_text_color(FILE *fp, TextMode attr)
{
  set_text_color(fp, attr, NO_COLOR);
}

void
set_text_color(FILE *fp, TextColor fg)
{
  set_text_color(fp, MODELESS, fg);
}

void
reset_text_color(FILE *fp)
{
  if (fp == stdout && !color_enabled()) return;
  if (fp == stderr && !color_enabled()) return;

  fprintf(fp, "%c[%dm", 0x1B, MODELESS);
}

void
colorize(FILE *fp, TextColor fg, TextMode mode, std::function<void()> func)
{
  set_text_color(fp, mode, fg);
  func();
  reset_text_color(fp);
}

void
colorize(FILE *fp, TextColor fg, std::function<void()> func)
{
  colorize(fp, fg, MODELESS, func);
}
