            [java.nio.file FileSystems StandardWatchEventKind])
   (:require [clj-stacktrace.repl :as stacktrace]
             [tachyon.core :as irc]
-            [demogorgon.twitter :as twitter])
-  (:use	[clojure.contrib.duck-streams :only (reader)]
+            [demogorgon.twitter :as twitter]
+            [clojure.contrib.sql :as sql])
+  (:use	[clojure.contrib.duck-streams :only (reader read-lines)]
         [demogorgon.config]))
 
 (defstruct watcher-instance :watch-service :events :thread :irc)

                       ((:callback file) (:irc @watcher) line)
                       (var-set files (assoc (var-get files)
                                        fn
                                        (assoc (get fn (var-get files)) :length (.getFilePointer ra))))
                       (recur (.readLine ra)))))
                 (.close ra)))))
         (.reset key))))))

(defn nh-stop [watcher]
  (.close (:watch-service @watcher)))

(defn insert-xlogfile-line-db [line]
  (let [data (parse-line line)]
    (let [record (assoc data :death_uniq (.replaceAll (:death data) ", while .*$", ""))]
      (sql/insert-records :xlogfile
                        record))))

(defn nh-init-db []
  (.info logger "re-initializing database..")
  (if (.exists (File. "/tmp/nh.db"))
    (.delete (File. "/tmp/nh.db")))
  (sql/with-connection db
    (sql/transaction
     (sql/create-table
      :xlogfile
      [:id "INTEGER PRIMARY KEY AUTOINCREMENT"]
      [:version "TEXT"]
      [:points "INT"]
      [:deathdnum "INT"]
      [:deathlev "INT"]
      [:maxlvl "INT"]
      [:dlev_name "TEXT"]
      [:hp "INT"]
      [:maxhp "INT"]
      [:deaths "INT"]
      [:deathdate "DATE"]
      [:birthdate "DATE"]
      [:uid "INT"]
      [:role "TEXT"]
      [:race "TEXT"]
      [:gender "TEXT"]
      [:align "TEXT"]
      [:name "TEXT"]
      [:death "TEXT"]
      [:death_uniq "TEXT"]
      [:conduct "TEXT"]
      [:turns "INT"]
      [:achieve "TEXT"]
      [:realtime "INT"]
      [:starttime "TIMESTAMP"]
      [:endtime "TIMESTAMP"]
      [:gender0 "TEXT"]
      [:align0 "TEXT"])
     (let [lines (read-lines (str (:un-dir config) "xlogfile"))]
       (doseq [line lines]
         (insert-xlogfile-line-db line)))))
  (.info logger "database initialized"))

(defn nh-start [watcher]
  (nh-init-db)
  (.start (:thread @watcher)))
