1//  Copyright (c) 2014 Couchbase, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// 		http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package flexible
16
17import (
18	"fmt"
19	"time"
20
21	"github.com/blevesearch/bleve/analysis"
22	"github.com/blevesearch/bleve/registry"
23)
24
25const Name = "flexiblego"
26
27type DateTimeParser struct {
28	layouts []string
29}
30
31func New(layouts []string) *DateTimeParser {
32	return &DateTimeParser{
33		layouts: layouts,
34	}
35}
36
37func (p *DateTimeParser) ParseDateTime(input string) (time.Time, error) {
38	for _, layout := range p.layouts {
39		rv, err := time.Parse(layout, input)
40		if err == nil {
41			return rv, nil
42		}
43	}
44	return time.Time{}, analysis.ErrInvalidDateTime
45}
46
47func DateTimeParserConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.DateTimeParser, error) {
48	layouts, ok := config["layouts"].([]interface{})
49	if !ok {
50		return nil, fmt.Errorf("must specify layouts")
51	}
52	var layoutStrs []string
53	for _, layout := range layouts {
54		layoutStr, ok := layout.(string)
55		if ok {
56			layoutStrs = append(layoutStrs, layoutStr)
57		}
58	}
59	return New(layoutStrs), nil
60}
61
62func init() {
63	registry.RegisterDateTimeParser(Name, DateTimeParserConstructor)
64}
65