(*
 * WRAPPER_CANON.ML-- 
 *
 * Copyright (C) 2009 Antoine Durand-Gasselin
 * Author: Antoine Durand-Gasselin <adg@crans.org>
 *
 * License: GPLv3
 *
 * Dependances: libperl4ocaml-dev (>= 0.9.5-2), libwww-mechanize-perl
 * Compilation: ocamlfind ocamlc -linkpkg -package unix,perl wrapper_canon.ml
 *
#use "topfind";;
#require "perl";;
#require "unix";;
*)

let (%) a b = Printf.sprintf a b;;
let (&) f x = f x

open Perl
open Unix
open Pl_WWW_Mechanize

let timestamp = (** on a besoin d'un timestamp *)
  "%d" % (int_of_float (Unix.time()))

(** {1 : Fonctions de conversion des options} *)
let filename = (** le nom du fichier pdf *) ref ""

let copies = ref 1
let _Copies () = "%d" % !copies

let papier = ref "a4"
let _MediaSize () = string_of_int (match String.lowercase (!papier) with
  | "a4" -> 5
  | "a3" -> 6
  | "a5" -> 16
  | "b4" -> 12
  | "b5" -> 13
  | "ltr" -> 1
  | "lgl" -> 2
  | "11x17" -> 3
  | "exec" -> 4
  | "com-10" -> 7
  | "monarch" -> 8
  | "c5 env" -> 9
  | "b5 env" -> 10
  | "dl env" -> 11
  | _ -> raise (Arg.Bad ("%s wrong papersize" % !papier)))

let papertype = ref "Ordinaire"
let _MediaType () = List.assoc !papertype& List.map (fun (x,y) -> y,x)
[ "0", "Ordinaire"; "2", "Recyclé"; "3", "Couleur"; "21", "Ordinaire (Epais)";
  "22", "Ordinaire (Fin)"; "1", "Papier épais 1"; "16", "Papier épais 2";
  "9", "Carte postale"; "10", "Carte postale"; "11", "Enveloppe";
  "6", "Transparent"; "23", "Transparent"; "24", "Couché"; "5", "Calque";
  "7", "Etiquettes"; "12", "Papier machine"; "14", "Pré-perforé" ]

let expand = ref false
let _FitSize () = if !expand then "1" else "0"

let duplex = ref true
let binding_long_edge = ref true
let finition = ref "none"
let _DuplexType() =
  if !finition = "book" or not !duplex then "0"
  else if !binding_long_edge then "2" else "1"

let finition = ref "none"
let _Sort() = match !finition with "none" -> "0" | _ -> "1"

let _StapleType () = List.assoc !finition
  [ "TopLeft","5"; "TopRight","6"; "BottomLeft","7"; "BottomRight","8";
    "Top","1"; "Bottom","2"; "Left","3"; "Right","4"; "none","0"; "book","9"]

let couleur = ref false
let _ColorMode () = if !couleur then "2" else "1"

(** {1: Le formulaire} *)
let fields () =
  [ "Url","http://"; "Mode","100"; "ManualNo","0"; "DocPasswd","";
    "WebUserName",""; "WebPasswd","";
    "PageMode","0"; "StartPage","1"; "EndPage","1";
    "Copies", _Copies();
    "MediaSize", _MediaSize();
    "MediaType", _MediaType();
    "ManualFeed", "0";
    "FitSize", _FitSize();
    "DuplexType", _DuplexType();
    "Sort", _Sort();
    "PunchPos","0";
    "StapleType", _StapleType();
    "BookType","2";
    "Annotation","2";
    "ColorMode", _ColorMode();

    "C_Render","0"; "C_RGB_Pro","1"; "C_CMYK_Pro","4";"C_OUT_Pro","1";
    "C_GRAY_Pro","1"; "C_Matching","0"; "SPOT_Color","1"; "C_Pure_B","1";
    "C_B_OVPrn","1"; "C_Bright", "100"; "C_Gray_Com","1";"C_OVR_EFF","1";
    "WidePrn","0"; "NupPrint","0"; "NupStart","0"; "Resolution","1";
    "HalfToneTxt","1"; "HalfToneGrp","1"; "HalfToneImg","1";
    "AstIntensity","2"; "AstText","0"; "AstGrap", "1"; "AstImag","1";
    "StoreBox","0"; "BoxNo","00"; "RGBDLName",""; "CMYKDLName","";
    "OUTDLName",""; "BOXName","";

    "Flag","Exec_Data_Pdf";
    "Dummy",timestamp;
    "Direct","100";
    "File", !filename
  ]

let set_positive r s =
  try let a = int_of_string s in assert (a>0); r := a
  with _ -> raise (Arg.Bad "copies doivent être un entier positif")

let options = Arg.align
  [ "-#", Arg.String (set_positive copies), "N imprime N copies";
    "-PageSize", Arg.Set_string papier, "FORMAT Format du papier";
    "-MediaType", Arg.Set_string papertype, "TYPE Type du papier";
    "-pdf-expand", Arg.Set expand, " Agrandir/Reduire en fonction du papier";
    "-one-sided", Arg.Clear duplex, " Impression recto";
    "-two-sided", Arg.Set duplex, " Impression recto/verso";
    "-two-sided-short-edge", Arg.Clear binding_long_edge,
      " Reliure sur le bord court";
    "-Monochrom", Arg.Clear couleur, " Impression en noir et blanc";
    "-Color", Arg.Set couleur, " Impression en couleurs";
    "-Finition", Arg.Set_string finition, "FINITION Finition: none | Top | TopLeft ... | Book";
  ]

let usage = "Usage: wrapper_canon [OPTIONS] FILE"

let argv = ref 0
let () = Arg.parse options (fun s -> incr argv; filename := s) usage

let () =
  if !argv <> 1 then raise (Arg.Bad "Wrong number of file")

(** {1 : Initialisations} *)
let printer = (** url de l'imprimante *)
  ref "https://imprimante.adm.crans.org/"

let b =
  (** On initialise le "browser" *)
  let sv = Perl.call_class_method "WWW::Mechanize" "new" [] in
  let browser = new Pl_WWW_Mechanize.www_mechanize sv in

    (* On a besoin d'un user_agent connu *)
    browser#agent_alias (List.nth browser#known_agent_aliases 1);

    (* On récupère un cookie, parce que les cookies c'est bon *)
    browser#get !printer;

    browser#get (!printer ^ "ppdf.cgi?Type=PDF&Dummy=%s" % timestamp);
    browser


(* On balance la sauce *)
let resp = b#submit_form ~form_name:"PDF_SEND_FORM" ~fields:(fields ()) ();;

print_string resp#as_string;;
