# frozen_string_literal: true

require "optparse"

module TinyDancer
  class CLI
    include TinyDancer::UI

    # @param args [Array<String>] all arguments to the CLI executable
    # @param token [String] your TinyPNG API token
    def initialize(argv0, *args, token: ENV["TINYPNG_API_TOKEN"])
      @this = argv0
      @args = args

      @options = {}
      @parser = OptionParser.new do |parser|
        parser.banner = "Usage: #{this} [options]"

        parser.on("-o", "--[no-]overwrite",
                  "Replace the original file with the tiny version") do |opt|
          @options[:overwrite] = opt
        end

        parser.on("-c", "--[no-]clobber",
                  "Overwrite the original file with the tiny version") do |opt|
          @options[:clobber] = opt
        end

        parser.on("-h", "--help", "Prints this help") do
          puts parser
          exit
        end
      end

      @parser.parse!(@args)
      @files = @args.dup

      raise ArgumentError, "no files given!" if @files.empty?

      @token = token
      @session = TinyDancer::Session.new(token: @token, **@options)
      @session.add_images(*@files)
    end

    def tinify!
      @session.tinify!
    end

    # @return [String]
    def inspect
      %(#<#{self.class.name}::0x#{object_id}>)
    end
  end
end
