require_relative "request_handler"

module Devops
  module API3
    module Handler
      class JobTask < RequestHandler

        def options
          params = @request.params
          options = {}
          ["project", "environment", "category", "type", "created_by", "status", "server_id", "max_number"].each do |k|
            options[k] = params[k] unless params[k].nil?
          end
          fill_date_params_for_searching(options)

          #attributes_keys = params.keys.select{|k| k =~ /attributes\.*/}
          #attributes_keys.each do |ak|
          #  options[ak] = params[ak]
          #end
          options
        end

        def all
          sort = extract_sort_params_for_searching
          limit = extract_limit_params_for_searching(10)
          Devops::Model::JobTask.where(options).sort(sort).limit(limit)
        end

        def all_latest
          # TODO:
          #Devops::Db.connector.latest_reports(options())
          []
        end

        def attributes name
          # TODO:
          #Devops::Db.connector.reports_attributes_values(name)
          []
        end

        def task id
          Devops::Model::JobTask.find(id)
        rescue Mongoid::Errors::DocumentNotFound => e
          raise Devops::Exception::RecordNotFound.new("JobTask '#{id}' does not exist")
        end

        def report id
          t = task(id)
          tstatus = t.status
          if tstatus == Worker::STATUS::IN_QUEUE
            return "Task '#{id}' has been queued", false
          end
          file = t.file
          raise Devops::Exception::RecordNotFound.new("JobTask '#{id}' file does not exist") unless File.exists? file
          completed = (tstatus == "completed" or tstatus == "failed")
          return Rack::Utils.escape_html(File.read(file).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')), completed
        end

        def status id
          t = task(id)
          t.status
        end

      end
    end
  end
end

