use fastly::http::header;
use fastly::{Error, Request, Response};
use libflate::gzip::Decoder;
use std::io::Read;

const BACKEND_NAME: &str = "origin_0";

// This function prevents responses on other compression formats
// so the content-encoding response header must be "gzip"
// and we can focus on gzip
#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
    let accept_encoding = match req.get_header(header::ACCEPT_ENCODING) {
        Some(accept_encoding_value) if accept_encoding_value.to_str().unwrap().contains("gzip") => {
            req.set_header(header::ACCEPT_ENCODING, "gzip");
            true
        }
        _ => false,
    };
    let mut response = req.send(BACKEND_NAME)?;
    let body = response.take_body();

    let body_orig = match response.get_header(header::CONTENT_ENCODING) {
        Some(_) => {
            let mut decoder = Decoder::new(body).unwrap();
            let mut decoded_data = Vec::new();
            decoder.read_to_end(&mut decoded_data).unwrap();

            String::from_utf8(decoded_data).unwrap()
        }
        None => body.into_string(),
    };

    // The following line is just a placeholder to your code.
    // Now it is a string, work on the response body and modify it at will
    let body_transformed = str::replace(
      &body_orig,
      "HTTP me!</h1>",
      "HTTP me (modified)!</h1>"
    );

    // Return a response with the new body
    if accept_encoding {
        response.remove_header(header::CONTENT_ENCODING);
        // The next header tells Fastly to compress your modified response
        // so you do not need to spend Compute CPU for this
        response.set_header("x-compress-hint", "on");
    }
    response.set_body(body_transformed);
    Ok(response)
}