#!/usr/bin/env ruby

require "birst_command"
require "optparse"

module BirstCL
  extend self

  def run
    set_options

    if @options[:version]
      puts "Birst_Command Version: #{Birst_Command::VERSION}"
      exit
    end

    if @options[:command]
      read_config_file
      execute_command
    end
  end

  def set_options
    @options = {}

    OptionParser.new do |opts|
      opts.banner = "Usage: birstcl -c <COMMAND> -a <ARGUMENTS>"

      opts.on("--verbose", "--[no-]verbose", "Run verbosely") do |v|
        @options[:verbose] = v
      end

      @options[:version] = false
      opts.on("--version", "--version", "Print version") do |v|
        @options[:version] = true
      end
      
      opts.on("-h","--help", "Show this message") do
        puts opts
        exit
      end

      @options[:command] = nil
      opts.on("-c","--command <COMMAND>","COMMAND is the snake_case Birst web API command") do |opt|
        @options[:command] = opt
      end

      @options[:arguments] = {}
      opts.on("-a","--args <ARGUMNETS>","ARGUMENTS is a JSON string of arguments to COMMAND") do |opt|
        @options[:arguments] = eval(opt)
      end

      @options[:config_full_path] = "#{ENV['HOME']}/.birstcl"
      opts.on("-s","--config_file <CONFIG FILE>", "Path to config file containing credentials (default: $HOME/.birstcl)") do |opt|
        @options[:config_full_path] = opt
      end

      @options[:write_cookie_full_path] = nil
      opts.on("-w","--write_cookie_file <COOKIE FILE>", "Path to cookie file to write") do |opt|
        @options[:write_cookie_full_path] = opt
      end

      @options[:read_cookie_full_path] = nil
      opts.on("-r","--read_cookie_file <COOKIE FILE>", "Path to cookie file to read") do |opt|
        @options[:read_cookie_full_path] = opt
      end
    end.parse!
  end


  def read_config_file
    Birst_Command.load_settings_from_file(@options[:config_full_path])
  end

  def write_cookie_file(file_full_path)
    return nil if file_full_path.nil?
    File.open(file_full_path, 'w') {|f| f.write(Marshal.dump(@session_cookie)) }
  end

  def read_cookie_file(file_full_path)
    return nil if file_full_path.nil?
    Marshal.load(File.read(file_full_path))
  end


  def execute_command
    @session_cookie = read_cookie_file(@options[:read_cookie_full_path])
    output = {}

    output[:command] = @options[:command]
    output[:arguments] = @options[:arguments]
    Birst_Command::Session.new auth_cookie: @session_cookie do |bc|
      output[:login_token] = bc.login_token
      output[:auth_cookies] = bc.auth_cookie.inspect
      output[:result] = bc.send(@options[:command], @options[:arguments])
      @session_cookie = bc.auth_cookie
    end
    puts "#{JSON.pretty_generate output}"
    write_cookie_file(@options[:write_cookie_full_path])
  end
end

BirstCL.run
