67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package switchcounter
|
|
|
|
import (
|
|
"encoding/csv"
|
|
"io"
|
|
"log"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/celrenheit/sandflake"
|
|
)
|
|
|
|
type Switch struct {
|
|
ID string `json:"id"`
|
|
Who string `json:"who"`
|
|
StartedAt time.Time `json:"started_at"`
|
|
EndedAt *time.Time `json:"ended_at"`
|
|
Duration time.Duration `json:"duration"`
|
|
}
|
|
|
|
// 2020-01-04 13:42:13 UTC
|
|
const timeFormat = `2006-01-02 15:04:05 MST`
|
|
|
|
func (s *Switches) ImportCSV(r io.Reader) ([]Switch, error) {
|
|
var result []Switch
|
|
rd := csv.NewReader(r)
|
|
rows, err := rd.ReadAll()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, row := range rows[1:] {
|
|
log.Printf("%v", row)
|
|
startedAtVal := row[1]
|
|
endedAtVal := row[2]
|
|
|
|
startedAt, err := time.Parse(timeFormat, startedAtVal)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
endedAt, err := time.Parse(timeFormat, endedAtVal)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
lenSeconds, err := strconv.ParseInt(row[3], 10, 64)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
g := sandflake.NewFixedTimeGenerator(startedAt)
|
|
id := g.Next()
|
|
sw := Switch{
|
|
ID: id.String(),
|
|
Who: row[0],
|
|
StartedAt: startedAt,
|
|
EndedAt: &endedAt,
|
|
Duration: time.Duration(lenSeconds) * time.Second,
|
|
}
|
|
|
|
result = append(result, sw)
|
|
}
|
|
|
|
return result, nil
|
|
}
|