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

  Copyright (C) 2003-2020 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
colorEnabled()
{
  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
mpmoColorSet(int p_colorBehaviour)
{
  colorBehaviour = p_colorBehaviour;
}

int
mpmoGetColorMode()
{
  return colorBehaviour;
}

int CDO_Color = 1;

void
set_text_color(FILE *fp, TextMode attr, TextColor fg)
{
  if (!colorEnabled()) return;
  if (!colorEnabled()) 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 && !colorEnabled()) return;
  if (fp == stderr && !colorEnabled()) 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);
}
