use fastly::{Error, Request, Response};
use lazy_static::lazy_static;
use regex::Regex;
use base64::{Engine as _, alphabet, engine::{self, general_purpose}};

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    log_fastly::init_simple("mylogs", log::LevelFilter::Info);
    lazy_static! {
        static ref RE: Regex = Regex::new(r"/views/(?P<path>[^/]*)").unwrap();
    }

    let url = req.get_path();

    if let Some(encoded) = RE
        .captures(url)
        .and_then(|cap| cap.name("path"))
        .map(|p| p.as_str().to_owned())
    {
      let decoded = engine::GeneralPurpose::new(
        &alphabet::URL_SAFE,
        general_purpose::PAD)
        .decode(encoded).unwrap();
      log::info!("Decoded path segment: {}", String::from_utf8(decoded)?);
    }
    
    let to_encode = "from=06/07/2013 query=\"Καλώς ορίσατε\"";

    // When base64-encoded material is sent as a part of a URL, the `encode_config` and
    // `decode_config` functions should be used, specifying that we want to use a character
    // set that is safe for use in URL's.
    //
    // `URL_SAFE_NO_PAD` can also be used to omit `=` padding. For example, the segment path
    // in this demo is encoded like this:

    log::info!("Encoded `{}` using URL_SAFE_NO_PAD: {}", to_encode, 
      engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD)
      .encode(to_encode)
    );

    // The normal base64 encoding of this text would include characters invalid in a URL path.
    // See below:
    
    log::info!("Encoded `{}` using STANDARD: {}", to_encode, 
      engine::GeneralPurpose::new(&alphabet::STANDARD, general_purpose::PAD)
      .encode(to_encode)
);

    Ok(Response::new())
}