# frozen_string_literal: true

4# frozen_string_literal: true

require "thor"

module Neetob
  class CLI
    class UI
      attr_accessor :shell

      def initialize
        @shell = Thor::Base.shell.new
      end

      def say(statement, color = Thor::Shell::Color::YELLOW)
        shell.say(statement, color)
      end

      def ask(question, echo = true)
        shell.ask(question, echo:)
      end

      def yes?(question)
        shell.yes?(question)
      end

      def error(statement, print_to_audit_log: true)
        shell.say(statement, Thor::Shell::Color::RED)
        if print_to_audit_log && (markdown_file = Thread.current[:markdown_file_name]).present?
          File.open(markdown_file, "a") do |f|
            f.puts statement
          end
        end
      end

      def success(statement, print_to_audit_log: true)
        shell.say(statement, Thor::Shell::Color::GREEN)
        if print_to_audit_log && (markdown_file = Thread.current[:markdown_file_name]).present?
          File.open(markdown_file, "a") do |f|
            f.puts statement
          end
        end
      end

      def info(statement, print_to_audit_log: true)
        shell.say(statement)
        if print_to_audit_log && (markdown_file = Thread.current[:markdown_file_name]).present?
          File.open(markdown_file, "a") do |f|
            f.puts statement
          end
        end
      end

      def indent(count)
        shell.indent(count) do
          yield
        end
      end

      def print_table(data, options = {})
        shell.print_table(data, options)
        if (markdown_file = Thread.current[:markdown_file_name]).present?
          header = data.first
          rows = data[1..]
          column_widths = header.map.with_index do |_, col|
            [header[col].to_s.length, *rows.map { |row| row[col].to_s.length }].max
          end
          markdown_table = "| " + header.map.with_index { |h, i| h.to_s.ljust(column_widths[i]) }.join(" | ") + " |\n"
          markdown_table += "|-" + column_widths.map { |w| "-" * w }.join("-|-") + "-|\n"
          rows.each do |row|
            markdown_table += "| " + row.map.with_index { |cell, i| cell.to_s.ljust(column_widths[i]) }.join(" | ") + " |\n"
          end
          File.open(markdown_file, "a") do |f|
            f.puts markdown_table
          end
        end
      end
    end
  end
end