import { padNumber } from "@veno-ui/utils";
import { MAP } from "./constants";
const defaultDateFormat = "YYYY-MM-DD HH:mm:ss";
function createDate(options) {
  let date;
  {
    if (!options) {
      date = /* @__PURE__ */ new Date();
    } else if (typeof options === "string") {
      date = new Date(options.replace(/-/g, "/"));
    } else {
      date = new Date(options);
    }
  }
  function tap(cb1, cb2) {
    const res = cb1();
    cb2(res);
    return res;
  }
  const ctx = {
    add(value, unit) {
      return tap(() => this.clone(), (cloned) => {
        const get = MAP[unit].get;
        const set = MAP[unit].set;
        if (set in cloned && get in cloned) {
          cloned[set](
            cloned[get]() + value
          );
        }
      });
    },
    subtract(value, unit) {
      return this.add(-value, unit);
    },
    startOf(unit) {
      return createDate(this.format(MAP[unit].startOf));
    },
    endOf(unit) {
      return createDate(this.format(MAP[unit].endOf));
    },
    format(value = defaultDateFormat) {
      const formatted = this.toObject();
      const { format, counter } = value.split("").reduce(({ format: format2, counter: counter2 }, key) => {
        if (key in formatted && format2[format2.length - 1] === key) {
          counter2[key] = counter2[key] || 1;
          counter2[key]++;
        } else {
          format2 += key;
        }
        return { format: format2, counter: counter2 };
      }, { format: "", counter: {} });
      return format.replace(/\w/g, (key) => {
        if (key in formatted) {
          const val = formatted[key];
          if (key in counter) {
            return padNumber(val, counter[key]);
          }
          return String(val);
        }
        return String(key);
      });
    },
    clone: () => createDate(date),
    unix() {
      return ~~(date.getTime() / 1e3);
    },
    valueOf() {
      return date.valueOf();
    },
    toDate() {
      return date;
    },
    toObject() {
      return {
        Y: date.getFullYear(),
        M: date.getMonth() + 1,
        D: date.getDate(),
        H: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds(),
        ms: date.getMilliseconds(),
        // weekday
        d: date.getDay()
      };
    }
  };
  return new Proxy(ctx, {
    get: (target, prop) => {
      return prop in target ? target[prop] : prop in date ? date[prop].bind(date) : void 0;
    },
    has: (target, prop) => {
      return prop in target || prop in date;
    }
  });
}
export {
  createDate,
  defaultDateFormat
};
//# sourceMappingURL=date.mjs.map
