#! /usr/bin/env ruby

# frozen_string_literal: true

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.realpath($PROGRAM_NAME)))

require 'yaml'
require 'json'
require 'optparse'
require "#{LKP_SRC}/lib/cci"
require "#{LKP_SRC}/lib/hash"

index = nil
field = nil
where = nil
condition = nil
show_type = nil

options = OptionParser.new do |opts|
  opts.banner = 'Usage: cci select -f $field -w $where $index'
  opts.separator '    search info from es db by sql'
  opts.separator '    eg.1: cci select -f suite,id,job_stage,testbox -w "id=\'xxx\'" -c \"order by id\" jobs'
  opts.separator '    eg.2: cci select -f \* -w "suite=\'xxx\' and job_stage=\'xxx\'" jobs'
  opts.separator 'options:'

  opts.on('-l', '--lab <LAB>', 'connect to lab') do |l|
    ENV['CCI_LAB'] = l.strip
  end

  opts.on('-f', '--field <field>', 'show field') do |f|
    field = f.strip
  end
  opts.on('-w', '--where <where>', 'select condition') do |w|
    where = w
  end
  opts.on('-c', '--condition <condition>', 'other condition') do |c|
    # because command line argument parsing will splits every space,
    # we use '-' to join every condition words.
    condition = c
  end
  opts.on('-s', '--show_type <show_type>', 'select show type: json or array') do |s|
    show_type = s
  end
  opts.on('-h', '--help', 'show this message') do
    die options
  end
end

if $PROGRAM_NAME == __FILE__
  die(options) if ARGV.empty?
  options.parse!(ARGV)
  index = ARGV[0] unless ARGV.empty?

  raise 'please input query index'                   if index.nil?
  raise 'Please input select field to show with -f'  if field.nil?

  show_type = get_show_type(field, show_type)
  select_field = get_select_field(field)

  data_hash = read_cci_credentials
  data_hash['query_field'] = select_field.join(',').to_s
  data_hash['query_index'] = index
  data_hash['query_where'] = where unless where.nil?
  data_hash['query_condition'] = condition unless condition.nil?
  response = es_opendistro_query(data_hash)

  if show_type == 'json'
    puts JSON.pretty_generate(response)
  else
    results = []
    response['hits']['hits'].each do |source|
      results << source['_source']
    end

    die('query results is empty') if results.empty?
    format_print(results, select_field)
  end
end