(ns auto-ap.time
  (:require [clj-time.core :as time]
            [clj-time.coerce :as coerce]
            [clj-time.format :as f]
            [auto-ap.logging :as alog]))

(defn localize [d]
  (time/to-time-zone d (time/time-zone-for-id "America/Los_Angeles")))

(defn as-local-time [d]
  (time/from-time-zone d (time/time-zone-for-id "America/Los_Angeles")))

(defn local-now []
  (time/to-time-zone (time/now) (time/time-zone-for-id "America/Los_Angeles")))

(def normal-date "MM/dd/yyyy")
(def iso-date "yyyy-MM-dd")
(def solr-date "yyyy-MM-dd'T'HH:mm:ss'Z'")

(def standard-time "MM/dd/yyyy hh:mm aa")

(defn parse-utc [v format]
  (try
    (f/parse (f/formatter format) v)
    (catch Exception _
      nil)))

(defn parse [v format]
  (try
    (time/from-time-zone (f/parse (f/formatter format) v)
                         (time/time-zone-for-id "America/Los_Angeles"))
    (catch Exception _
      nil)))

(defn unparse [v format]
  (try
    (f/unparse (f/formatter format) v)
    (catch Exception e
      (alog/warn ::cant-unparse :error e)
      nil)))

(defn unparse-local [v format]
  (try

    (f/unparse (f/with-zone (f/formatter format) (time/time-zone-for-id "America/Los_Angeles")) v)
    (catch Exception _
      nil)))


(defn day-of-week-seq [day]
  (let [next-day (loop [d (local-now)]
                   (if (= (time/day-of-week d) day)
                     d
                     (recur (time/plus d (time/days 1)))))]
    (iterate #(time/plus % (time/days 7)) next-day)))

(defn local-today []
  (coerce/in-time-zone (time/now) (time/time-zone-for-id "America/Los_Angeles")))


(defn last-monday []
  (loop [current (local-today)]
    (if (= 1 (time/day-of-week current))
      current
      (recur (time/minus current (time/days 1))))))
      