 ; Iyye - AI agent
-; Copyright (C) 2016-2017  Sasha Yumzya
+; Copyright (C) 2016-2018  Sasha Yumzya
 
 ; This program is free software: you can redistribute it and/or modify
 ; it under the terms of the GNU Affero General Public License as

; along with this program.  If not, see <http://www.gnu.org/licenses/>.

(ns iyye.bios.persistence
   (:require
     [clojure.tools.logging :as log]
     [extras.mongowrapper :as mongo]))

(defn local-time-to-string []
  (let [ date (java.util.Date.)]  (.format (java.text.SimpleDateFormat. "MM_dd_yyyy_HH_mm_ss") date)))

(def iyye-name (ref ()))
(def iyye-main "iyye_main")

(defn iyye-exists? [name]
  (let [entry (mongo/get-entry iyye-main "iyye_list" {:name name})]
    (if (first entry)  true false)))

(defn add-iyye [name]
  (if (iyye-exists? name)
    false
    (mongo/add-entry iyye-main "iyye_list" {:name name :time (local-time-to-string)} )))

(defn list-iyye []
  (log/info "nothing list")
  (let [entries (mongo/get-entry iyye-main "iyye_list" {})]
    (if entries (map :name entries)  false)))

(defn set-current-iyye [name]
  (dorun
    [(add-iyye name)
    (dosync (ref-set iyye-name name))]))

(defn load-current-iyye [name]
  (dosync (ref-set iyye-name name)))

(defn load-days []
  (mongo/get-count iyye-main (str "days_" @iyye-name) {}))

(defn write-io-to-db [days IO dir input]
  (let [doc (str "IO_day_" days)
        dbname (str @iyye-name "_IO_" (:name IO))
        entry {:time (local-time-to-string) dir input}]
    (mongo/add-entry dbname doc entry)))

(defn write-knowledge-to-db [doc-name fact]
  (let [dbname (str @iyye-name "_knowledge")]
    (log/info "add list: " (str fact))
    (mongo/add-entry dbname doc-name fact)))

; (apply str (rest (str (:When {:When :ALWAYS}))))

(defn read-knowledge-from-db [doc-name query]
  (let [dbname (str @iyye-name "_knowledge")]
    (mongo/get-entry dbname doc-name query)))
