require 'json'

class Api::BuildController < ApplicationController
  skip_before_filter :verify_authenticity_token # Safe to skip, as no web form is attached to this

  # /build/:id
  # /build/job/:job_name/:build_id
  def show
    if params.has_key?(:job_name) && params.has_key?(:build_id)
      @build = SmocaBuild.find_by(build_id: params[:build_id], job_name: params[:job_name])
    elsif params.has_key?(:id)
      @build = SmocaBuild.find_by(id: params[:id])
    else
      render json: {error: 'Must either provide a parameter of "id" or parameters ["job_name", "build_id"]'}.to_json, :status => 404
    end

    if @build
      render json: @build
    else
      render json: {:error => 'not found'}.to_json, :status => 404
    end
  end

  def create
    build = SmocaBuild.new(build_params)

    if build.valid?
      build.save
      logger.debug "Saved new SmocaBuild record: #{build.id}"
      render json: build
    else
      logger.error "Encountered issue creating new SmocaBuild record. #{build.errors.messages}"
      render json: {:error => build.errors.messages}.to_json, :status => 400
    end
  end

  def update
    begin
      build = SmocaBuild.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      return render json: {:error => 'Record Not Found'}, :status => 404
    end

    build.update(build_params)

    if build.valid?
      render json: build, :status => 200
    else
      render json: {:error => build.errors.messages}.to_json, :status => 400
    end
  end

  private def build_params
    params.permit(:result, :developer, :environment, :initiated_at, :build_id, :job_name, :queue_id, :cancelled, :pending)
  end
end
