require "genZPK/version"
require 'genZPK/templates'
require 'tempfile'
require 'nokogiri'
require 'highline/import'

class Object
  def not_nil?
    !nil?
  end
end

module GenZPK
  def getZdpack
    if File.exists? '/usr/local/zend/bin/zdpack'
      '/usr/local/zend/bin/zdpack'
    else
      nil
    end
  end

  def executablePath (executable=String.new)
    if executable.include? '/'
      if File.exists? executable
        executable
      else
        nil
      end
    else
      whichOut = `which #{executable}`.chomp!
      if whichOut =~ /\/usr\/bin\/which: no (.*) in \(.*\)/
        nil
      else
        if File.exists? whichOut
          whichOut
        else
          nil
        end
      end
    end
  end

  def getEditor
    if ENV['EDITOR'].nil?
      ['nano', 'vi'].each do |x|
        editor = executablePath x
        if not editor.nil?
          return editor
        end
      end
      raise "Valid text editor could not be found. Please specify one in the EDITOR environment variable and/or check your PATH."
    else
      editor = executablePath ENV['EDITOR']
      if not editor.nil?
        editor
      else
        ['nano', 'vi'].each do |x|
          editor = executablePath x
          if not editor.nil?
            return editor
          end
        end
        raise "Valid text editor could not be found. Please specify one in the EDITOR environment variable and/or check your PATH."
      end
    end
  end

  def yesno(prompt = 'Continue?', default = true)
    a = ''
    s = default ? '[Y/n]' : '[y/N]'
    d = default ? 'y' : 'n'
    until %w[y n].include? a
      a = ask("#{prompt} #{s} ") { |q| q.limit = 1; q.case = :downcase }
      a = d if a.length == 0
    end
    a == 'y'
  end

  def requireCondition(condition, message)
    if not condition
      puts message
      exit -1
    end
  end

  def doConfigure
    if not File.exists?(File.expand_path '~/.genZPK')
      FileUtils.mkpath(File.expand_path '~/.genZPK')
    end

    if not File.exists?(File.expand_path '~/.genZPK/checks.xml')
      File.new(File.expand_path('~/.genZPK/checks.xml'), 'w')
    end

    checksFile = File.open(File.expand_path('~/.genZPK/checks.xml'), 'r')
    tmpChecksFile = Tempfile.new 'checks'
    while buff = checksFile.read(4096)
      tmpChecksFile.write(buff)
    end
    tmpChecksFile.rewind
    checksFile.close

    editor = getEditor
    system("#{editor} #{tmpChecksFile.path}")

    begin
      content = tmpChecksFile.read
      tmpChecksFile.rewind
      doc = Nokogiri::XML(content) { |config| config.options = Nokogiri::XML::ParseOptions::STRICT }
    rescue Nokogiri::XML::SyntaxError => e
      if yesno("Invalid XML entered. Would you like to reopen the file?")
        loop do
          system("#{editor} #{tmpChecksFile.path}")
          begin
            content = tmpChecksFile.read
            tmpChecksFile.rewind
            doc = Nokogiri::XML(content) { |config| config.options = Nokogiri::XML::ParseOptions::STRICT }
            break
          rescue
            if not yesno("Invalid XML entered. Would you like to reopen the file?")
              exit -1
            end
          end
        end
      else
        exit -1
      end
    end

    checksFile = File.open(File.expand_path('~/.genZPK/checks.xml'), 'w+')

    while buff = tmpChecksFile.read(4096)
      checksFile.write(buff)
    end

    checksFile.close
    tmpChecksFile.close
    tmpChecksFile.unlink
  end
end