(*********************************************************************************)
(*                Chamo                                                          *)
(*                                                                               *)
(*    Copyright (C) 2003-2021 Institut National de Recherche en Informatique     *)
(*    et en Automatique. All rights reserved.                                    *)
(*                                                                               *)
(*    This program is free software; you can redistribute it and/or modify       *)
(*    it under the terms of the GNU Lesser General Public License version        *)
(*    3 as published by the Free Software Foundation.                            *)
(*                                                                               *)
(*    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, write to the Free Software                *)
(*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA                   *)
(*    02111-1307  USA                                                            *)
(*                                                                               *)
(*    Contact: Maxence.Guesdon@inria.fr                                          *)
(*                                                                               *)
(*********************************************************************************)

(** Main module of the editor. *)

open Chamo
open Stk.Misc
let _ = Args.parse ()

(*
let () = Logs.Src.set_level Stk.Texture.src (Some Logs.Warning)
let () = Logs.Src.set_level Stk.Log.src (Some Logs.Warning)
let () = Logs.Src.set_level Stk.Textbuffer.src (Some Logs.Warning)
let () = Logs.Src.set_level Stk.Textview.src (Some Logs.Warning)
let () = Logs.Src.set_level Stk.Render.src (Some Logs.Warning)
*)
open Stk.Misc
let () = let> () = Tsdl.Sdl.(init Init.(video+events)) in ()

let () = Lwt_main.run (Stk.App.init
	(*~sdl_events_mode:`Detached*)
	(*~event_delay:10*) ())

let main () =
  let logwin = Log.get_log_window () in
  Logs.set_reporter (Stk.Textlog.reporter logwin#textlog);

  let () =
   let json = {|
     { "minibuffer": { inherits: "entry" },
       "keystate": { inherits: "label",
            bg_color:"blue",
            fill: true,
            fg_color:"white" },
       "minibuffer_vp": {
         inherits: "scrollbox",
         border_width: 1,
         border_color_focused: "green"
       }
     }
     |}
    in
    let json = Yojson.Safe.from_string json in
    Stk.Theme.extend_current_from_json json
  in

  let waiter, wakener = Lwt.wait () in
  Gui.on_last_window_close := (Lwt.wakeup wakener) ;
(*  ignore(Log.get_log_window());*)

  Lwt.async_exception_hook :=
    (fun e -> Log.err (fun m -> m "%s" (Printexc.to_string e)));
  List.iter Commands.async_command (!Args.init_commands @ !Args.commands);
  View.iter_factories
    (fun f -> Misc.catch_print_exceptions (fun () -> f#on_start) ());

  begin
    try
      if Sys.file_exists !Layout.layout_file then
        try
          let layout = Layout.load_layout !Layout.layout_file in
          Layout.create_windows_of_layout layout
        with
          Failure s
        | Sys_error s ->
            prerr_endline s;
            raise Not_found
      else
        raise Not_found
    with
      Not_found ->
        match !Gui.gui_windows with
          [] -> ignore(Gui.create_window())
        | _ -> ()
  end;
  begin
    match !Gui.active_window, !Gui.gui_windows with
      None, w :: _ -> Gui.active_window := Some w
    | _ -> ()
  end;
  let on_file file =
    Commands.async_launch_command "open_file" [| file |]
  in
  List.iter on_file !Args.remaining;
  let lw = Log.get_log_window () in
  lw#window#move ~x: 10 ~y:10;
  (*Log.show_log_window ();*)

  let%lwt () = Lwt.pick [Stk.App.run(); waiter] in

  View.iter_factories
    (fun f -> Misc.catch_print_exceptions (fun () -> f#on_exit) ());
  Commands.async_command Constant.com_on_exit;

  Lwt.return_unit

let () = Lwt_main.run (main ())
