;; This buffer is for text that is not saved, and for Lisp evaluation.
;; To create a file, visit it with C-x C-f and enter text in its buffer.

(def things (with-open [reader (io/reader "/Volumes/Data/Dropbox/Covert Integreat - Shared Files/vendors")] (doall (csv/read-csv reader :separator \tab))))

(def to-transform (reduce 
       (fn [things [name _ default-expense-account address1 address2 tax-id _ _ primary-contact primary-email primary-phone secondary-contact secondary-email secondary-phone]] 
         (conj things {
                       :name name
                       :default-expense-account default-expense-account
                       :address1 address1
                       :address2 address2
                       :tax-id tax-id
                       :primary-contact primary-contact
                       :primary-email primary-email
                       :primary-phone primary-phone
                       :secondary-contact secondary-contact
                       :secondary-email secondary-email
                       :secondary-phone secondary-phone


         } ))
       []  things))

(defn replace-expense-account [x]
  (update x :default-expense-account
          (fn [e]
              (some->
               (first (re-find #"([0-9]+)" e))
               (Integer/parseInt ))
              )))

(defn replace-address [x]
  (let [[_ city zip] (re-find #"(.*), [^0-9]*([0-9]+)" (:address2 x))]
    (-> x
        (assoc :address
               {:street1 (:address1 x)
               :street2 ""
               :city city 
               :state "CA"
               :zip zip
               })
        (dissoc :address1 :address2))))

(defn add-default-expense-account [x]
  (update x :default-expense-account #(or % 0)))

(defn extract-email [x]
  (update x :primary-email
          (fn [email]
              (second (re-find #"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63})" email)))))

(def import (->> to-transform
           (map replace-expense-account)
           (map replace-address)
           (map add-default-expense-account)
           (map extract-email)
           (filter #(s/valid? :auto-ap.entities.vendors/vendor %))))
  )
(-> to-transform
    (replace-expense-account)
    (drop 2)
    (take 10))
