(*
 *    _  _   ____                         _  
 *  _| || |_/ ___|  ___ _ __  _ __   ___ | | 
 * |_  ..  _\___ \ / _ \ '_ \| '_ \ / _ \| | 
 * |_      _|___) |  __/ |_) | |_) | (_) |_| 
 *   |_||_| |____/ \___| .__/| .__/ \___/(_) 
 *                     |_|   |_|             
 *
 * Personal Social Web.
 *
 * Copyright (C) The #Seppo contributors. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *)

(* https://datatracker.ietf.org/doc/html/rfc7565 *)
type t = T of Uri.t

let scheme = "acct"

let of_uri u =
  assert ("acct" |> String.equal scheme);
  match
    u |> Uri.scheme,
    u |> Uri.user,
    u |> Uri.host,
    u |> Uri.port,
    u |> Uri.path,
    u |> Uri.query,
    u |> Uri.fragment
  with
  | Some "acct",
    Some _,
    Some _,
    None,
    "",
    [],
    None
    -> Some (T u)
  | _
    -> None

let make ~local ~domain () =
  match Uri.make
          ~scheme
          ~userinfo:local
          ~host:domain
          ()
        |> of_uri with
  | None ->
    Printf.sprintf "%s @%s@%s" __LOC__ local domain
    |> failwith
  | Some u -> u

let rx_scheme = scheme ^ {|:\|@|}
let rx_user = {|[^@: ]+|}
let rx_host = {|[^ :/\?#]+|}
let rx' = {|^\(|} ^ rx_scheme ^ {|\)?\(|} ^ rx_user ^ {|\)@\(|} ^ rx_host ^ {|\)$|}
let rx = rx' |> Str.regexp

let of_string s =
  if not (Str.string_match rx s 0)
  then Error ("doesn't match /" ^ rx' ^ "/")
  else
    Ok (make
          ~local:(Str.matched_group 2 s)
          ~domain:(Str.matched_group 3 s)
          () )

let to_string ?(prefix = scheme ^ ":") (T u) =
  Printf.sprintf "%s%s@%s"
    prefix
    (u |> Uri.user |> Option.value ~default:"")
    (u |> Uri.host |> Option.value ~default:"")

let pp_hum ppf uri = Format.pp_print_string ppf (to_string ~prefix:"@" uri)
