#!/usr/bin/env ruby

$:.insert(0, 'lib')

require 'thor'
require 'rly'
require 'pry'
require 'mm2ep_depend'
require 'pp'
require 'logger'

module Mm2ep
  module Depend

    class ParseCli < Thor
      desc 'parse OPTIONS INFILE VARS', 'Parse INFILE into tokens and evaluate VARS'
      method_option :logfile, :type => :string, :aliases => '-l', :default => '-', :desc => "Logger with logfile"
      def parse(infile, *vars)
        unless options[:logfile].eql? '-'
          logger = Logger.new("#{options[:logfile]}.log")
        else
          logger = Logger.new(STDOUT)
        end
        line = File.read(infile).gsub(/\n/,'')
        lexer = Lexer.new(logger)
        parser = Parser.new(lexer)
        tab_vars = {}
        vars.each do |var|
          tab_vars[var.split('=')[0]] = var.split('=')[1]
        end

        # Give vars name and value from shell command to parser
        parser.names=tab_vars

        token = parser.parse(line.chomp, true)
        pp token
        puts "RAW : #{line}"
        puts "EVAL: #{token.to_s}"
        parser.check_grammar line, token
        exit 1 unless !token.nil? && token.errors.empty?

        puts "RESULT: #{token.compute}"

      end
    end
  end
end

Mm2ep::Depend::ParseCli.start(ARGV)