/*
** Module   : HttpResponseHeader.java
** Abstract : A test for a HTTP response header.
**
** Copyright (c) 2021, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
** 001 CA  20210827 Created initial version.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.goldencode.harness.test;

import org.apache.http.*;

import com.goldencode.harness.*;

/**
 * A test applied to a response header.
 */
public class HttpResponseHeader
extends Report
implements WebResponseTestable
{
   /** The header name. */
   private String name;
   
   /** The expected header value. */
   private String value;
   
   /** The variable to save the path's value. */
   private String variable;

   /** The resource pool to store the variable. */
   private ResourcePool pool;

   /**
    * Configure a new header test.
    * 
    * @param    name
    *           The header name.
    * @param    value
    *           The expected header value (can be <code>null</code>).
    * @param    variable
    *           The variable name.
    * @param    pool
    *           The resource pool, to save the variable.
    */
   public HttpResponseHeader(String name, String value, String variable, ResourcePool pool)
   {
      this.name = name;
      this.value = value;
      this.variable = variable;
      this.pool = pool;
   }

   /**
    * Execute the test.  Exactly one {@link #name header} must exist, and its value must match exactly with the
    * {@link #value expected value} (if it was set).
    */
   @Override
   public void execute(HttpResponse response)
   {
      Header[] headers = response.getHeaders(name);
      
      if (headers.length != 1)
      {
         setStatus(Status.FAILED, "Exactly one header '" + name + "' must exist!");
         return;
      }
      
      if (value != null && !value.equals(headers[0].getValue()))
      {
         setStatus(Status.FAILED, 
                   "For header '" + name + "' expected '" + value + "' but found '" + headers[0].getValue() + "'");
         return;
      }
      
      setStatus(Status.PASSED, null);
      
      if (variable != null)
      {
         pool.createVariable(variable, headers[0].getValue());
      }
   }
}
