use chrono::{Utc, FixedOffset};
use fastly::geo::{geo_lookup};
use fastly::{Error, Request, Response};

const HOUR: i32 = 3600;

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
    let geo = req.get_client_ip_addr().and_then(geo_lookup).unwrap();

    match geo.utc_offset() {
        Some(fastly_offset) => {
            let offset = FixedOffset::east_opt(fastly_offset.whole_seconds()).unwrap();
            let utc_dt = Utc::now();
            let local_dt = utc_dt.with_timezone(&offset);

             // Add TZ in ISO8601 format
            req.set_header("tz-offset-iso8601", local_dt.format("%z").to_string());
            // Parse the time offset into a decimal number of hours
            req.set_header("tz-offset-hours", format!("{:.3}", (offset.utc_minus_local() / HOUR)));
            // Round to a whole hour
            req.set_header("tz-hour", (offset.utc_minus_local() / HOUR).to_string());
            // Round to nearest even hour
            req.set_header(
                "tz-evenhour",
                ((offset.utc_minus_local() as f32 / HOUR as f32 / 2.0).round() as i32 * 2).to_string(),
            );
        }
        None => {println!("The geolocation database does not have a time zone offset for this IP address");}
    }
 
    Ok(req.send("origin_0")?)
}