package types

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

// TimeText time text
type TimeText string

// DateText date text
type DateText string

// const
const (
	timeFormat = `2006-01-02 15:04:05`
	dateFormat = `2006-01-02`
)

// Value implements the driver.Valuer interface
func (t TimeText) Value() (driver.Value, error) {
	t1, err := time.ParseInLocation(timeFormat, string(t), time.Local)
	if err != nil {
		return nil, err
	}
	return TimeText(t1.Format(timeFormat)), nil
}

// Scan implements the sql.Scanner interface
func (t *TimeText) Scan(src interface{}) error {
	v, ok := src.(time.Time)
	if !ok {
		return errors.New("bad time.Time type assertion")
	}
	*t = TimeText(v.Format(timeFormat))
	return nil
}

// Value implements the driver.Valuer interface
func (t DateText) Value() (driver.Value, error) {
	t1, err := time.ParseInLocation(dateFormat, string(t), time.Local)
	if err != nil {
		return nil, err
	}
	return DateText(t1.Format(dateFormat)), nil
}

// Scan implements the sql.Scanner interface
func (t *DateText) Scan(src interface{}) error {
	v, ok := src.(time.Time)
	if !ok {
		return errors.New("bad time.Time type assertion")
	}
	*t = DateText(v.Format(dateFormat))
	return nil
}