require 'json'

class Api::TestCaseResultController < ApplicationController
  skip_before_filter :verify_authenticity_token # Safe to skip, as no web form is attached to this
  before_action :set_build, only: [:create]

  # GET /test_case_result/:id
  def show
    begin
      tc = TestCaseResult.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      return render json: { error: "Unable to locate provided test case id: #{params[:id]}" },
                    status: 404
    end

    return render json: tc, status: 200
  end

  def create
    name              = params[:name]
    result            = params[:result]
    exception_class   = params[:exception_class] # Optional, nil if not provided
    exception_message = params[:exception_message] # Optional, nil if not provided

    if name.nil?
      return render json: { error: 'Unable to create test case result. Must provide "name" of test case'},
                    status: 400
    end

    t_case_id = lookup_or_create_testcase(name).id
    if t_case_id.nil?
      return render json: { error: 'Issue creating test case. Check error logs' },
                    status: 400
    end

    logger.info "Adding Test Case ID #{t_case_id} to Build ID #{@build.id}"
    t_result = @build.test_case_results.create(result: result,
                                               test_case_id: t_case_id,
                                               exception_class: exception_class,
                                               exception_message: exception_message,
                                               screenshot_url: params[:screenshot_url],
                                               backtrace: params[:backtrace],
                                               failing_line: params[:failing_line])
    if t_result.valid?
      return render json: t_result
    else
      return render json: { error: 'Unable to create test case result.',
                            error_messages: t_result.errors.messages },
                    status: 400
    end
  end

  # Looks up or creates a TestCase Object
  # @param test_case_name [String] The name of the test case
  # @return [TestCase] if test case found or created
  # @return [NilClass] if there was a problem creating the test case
  private def lookup_or_create_testcase(test_case_name)
    test_case = TestCase.find_by(name: test_case_name)
    return test_case unless test_case.nil?

    created_case = TestCase.create(name: test_case_name)
    if created_case.valid?
      logger.info "Created new test case. Name: #{test_case_name}, ID: #{created_case.id}"
      return created_case
    else
      logger.error "Issue creating test case. #{created_case.errors.messages}"
      return nil
    end
  end

  private def set_build
    begin
      @build = SmocaBuild.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      return render json: { error: "Unable to find build with id #{params[:id]}"},
                    status: 404
    end
  end
end
