package utils

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type JsonTime struct {
	time.Time
}

const timeFormat = "2006-01-02 02:05:03"

func (this JsonTime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", this.Format(timeFormat))
	return []byte(stamp), nil
}

func (ct *JsonTime) UnmarshalJSON(b []byte) (err error) {
	s := string(b)
	if s == "null" || s == "" {
		return
	}
	ct.Time, err = time.Parse(timeFormat, s)
	return
}

// Value insert timestamp into mysql need this function.
func (t JsonTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof time.Time
func (t *JsonTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JsonTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
