# frozen_string_literal: true

require_relative 'base_controller'
require_relative '../models/benchmark'
require_relative '../models/hardware'
require_relative '../models/test'

# /test routes
class TestController < BaseController

  get '/test' do
    redirect('/test/list')
  end

  get '/test/list' do
    tests = Test.reverse(:updated_at).limit(10).all()

    erb :'test/index', locals: {
      title: 'List of Tests',
      tests: tests
    }
  end

  get '/test/add' do
    hardware = Hardware.order(:name).all()
    benchmarks = Benchmark.order(:name).all()

    erb :'test/add', locals: {
      title: 'Add Test',
      hardware: hardware,
      benchmarks: benchmarks
    }
  end
  post '/test/add' do
    tst = Test.create(
      name: params[:test_name],
      hardware_id: params[:test_hardware],
      description: params[:test_description]
    )

    # create an array of the selected benchmarks
    benchmarks = Array(params[:test_benchmarks])
    # associate the benchmarks to the test
    benchmarks.each do |b|
      tst.add_benchmark(b)
    end

    redirect "/test/#{tst.id}"
  end

  get '/test/:test_id' do
    tst = Test.where(id: params[:test_id]).first()
    erb :'test/view', locals: {
      title: tst.name,
      test: tst
    }
  end

  get '/test/:test_id/edit' do
    tst = Test.where(id: params[:test_id]).first()
    hardware = Hardware.order(:name).all()
    benchmarks = Benchmark.order(:name).all()

    erb :'test/edit', locals: {
      title: "Editing: #{tst.name}",
      test: tst,
      hardware: hardware,
      benchmarks: benchmarks
    }
  end

  post '/test/:test_id/edit' do
    tst = Test.where(id: params[:test_id]).first()

    tst.update(
      name: params[:test_name],
      hardware_id: params[:test_hardware],
      description: params[:test_description]
    )

    selected_benchmarks = Array(params[:test_benchmarks])

    # remove benchmarks no longer associated with the test
    tst.benchmarks.dup.each do |b|
      tst.remove_benchmark(b.id) unless selected_benchmarks.include?(b.id)
    end

    # associate the benchmarks to the test
    selected_benchmarks.each do |b|
      tst.add_benchmark(b) unless tst.benchmark?(b)
    end

    redirect "/test/#{tst.id}"
  end

end
