(ns auto-ap.import.manual.common
  (:require [auto-ap.datomic.accounts :as d-accounts]
            [auto-ap.parse.util :as parse-u]
            [clojure.string :as str]))

(defn parse-amount [i]
  (try
    (Double/parseDouble (str/replace (or  (second
                                           (re-matches #"[^0-9\.,\\-]*([0-9\.,\\-]+)[^0-9\.,]*" (:amount i)))
                                          "0")
                                     #"," ""))
    (catch Exception e
      (throw (Exception. (str "Could not parse total from value '" (:amount i) "'") e)))))

(defn parse-account-numeric-code [i]
  (try
    (when-let [account-numeric-code (:account-numeric-code i)]
      (:db/id (d-accounts/get-account-by-numeric-code-and-sets (Integer/parseInt account-numeric-code)
                                                               ["default"])))
    (catch Exception e
      (throw (Exception. (str "Could not parse expense account from value '" (:account-numeric-code i) "'") e)))))

(defn parse-date [{:keys [raw-date]}]
  (when-not
      (re-find #"\d{1,2}/\d{1,2}/\d{4}" raw-date)
    (throw (Exception. (str "Date " raw-date " must match MM/dd/yyyy"))))
  (try 

    (parse-u/parse-value :clj-time "MM/dd/yyyy" raw-date)
    (catch Exception e
      (throw (Exception. (str "Could not parse date from '" raw-date "'") e)))))

(defn parse-or-error [key f]
  (fn [x]
    (try
      (assoc x key (f x))
      (catch Exception e
        (update x :errors conj {:info (.getMessage e)
                                :details (str e)})))))

(defn assoc-or-error [m k f]
  (try
    (assoc m k (f))
    (catch Exception e
      (update m :errors conj {:info (.getMessage e)
                              :details (str e)}))))
