/*
Handler for the Interval By ID API
Status code 404 - interval not found
Status code 400 - interval still in use
Status code 500 - unanticipated issues
api/v1/interval
*/
482488
func intervalByIdHandler(w http.ResponseWriter, r *http.Request) {
	if r.Body != nil {
		defer r.Body.Close()
	}

	// URL parameters
	vars := mux.Vars(r)
	id, err := url.QueryUnescape(vars["id"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error un-escaping the value id: " + err.Error())
		return
	}

	switch r.Method {
	case http.MethodGet:
		// Get the interval
		e, err := getIntervalById(id)
		if err != nil {
			switch x := err.(type) {
			case *errors.ErrIntervalNotFound:
				http.Error(w, x.Error(), http.StatusNotFound)
			default:
				http.Error(w, x.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}
		encode(e, w)
	case http.MethodDelete:
		if err = deleteIntervalById(id); err != nil {
			switch err.(type) {
			case *errors.ErrDbNotFound:
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			case *errors.ErrIntervalStillUsedByIntervalActions:
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("true"))
	}

}
658670
func FlushInterval(interval time.Duration) Option {
	return func(c *client) {
		c.flushInterval = interval
	}
}
616932
func (mc MongoClient) UpdateInterval(interval contract.Interval) error {
	var mapped models.Interval
	id, err := mapped.FromContract(interval)
	if err != nil {
		return err
	}

	mapped.TimestampForUpdate()

	return mc.updateId(db.Interval, id, mapped)
}
1345137
func (a *BeginFrameArgs) SetInterval(interval float64) *BeginFrameArgs {
	a.Interval = &interval
	return a
}
184620
func (mc MongoClient) UpdateIntervalAction(action contract.IntervalAction) error {
	var mapped models.IntervalAction
	id, err := mapped.FromContract(action)
	if err != nil {
		return err
	}

	mapped.TimestampForUpdate()

	return mc.updateId(db.IntervalAction, id, mapped)
}
333852
func (i *InmemSink) getInterval() *IntervalMetrics {
	intv := time.Now().Truncate(i.interval)
	if m := i.getExistingInterval(intv); m != nil {
		return m
	}
	return i.createInterval(intv)
}
1271077
func (animation *AnimationSet) SetInterval(interval int64) {
	simlog.FuncIn()
	animation.interval = interval
	simlog.FuncOut()
}
1009507
func (s *SamplingTargetDocument) SetInterval(v int64) *SamplingTargetDocument {
	s.Interval = &v
	return s
}
883167
func (s *server) HeartbeatInterval() time.Duration {
	s.mutex.RLock()
	defer s.mutex.RUnlock()
	return s.heartbeatInterval
}
234763
func PollingInterval(i int) Option {
	return func(p *Plugin) error {
		p.PollingInterval = i
		return nil
	}
}
1316338
func (e IntervalActionInfo) Url() string {
	url := fmt.Sprintf("%s://%s:%v", e.Protocol, e.Host, e.Port)
	return url
}
502672
func (c *Config) UpdateStatusHookInterval() time.Duration {
	// TODO(wallyworld) - remove this work around when possible as
	// we already have a defaulting mechanism for config.
	// It's only here to guard against using Juju clients >= 2.2
	// with Juju controllers running 2.1.x
	raw := c.asString(UpdateStatusHookInterval)
	if raw == "" {
		raw = DefaultUpdateStatusHookInterval
	}
	// Value has already been validated.
	val, _ := time.ParseDuration(raw)
	return val
}
978279
func (c *Client) UpdateIntervalAction(from contract.IntervalAction) (err error) {
	check, err := c.IntervalActionByName(from.Name)
	if err != nil && err != redis.ErrNil {
		return err
	}
	if err == nil && from.ID != check.ID {
		// IDs are different -> name not unique
		return db.ErrNotUnique
	}

	from.Modified = db.MakeTimestamp()
	err = mergo.Merge(&from, check)
	if err != nil {
		return err
	}

	action := models.NewIntervalAction(from)
	data, err := json.Marshal(action)
	if err != nil {
		return err
	}

	conn := c.Pool.Get()
	defer conn.Close()

	_ = conn.Send("MULTI")
	deleteObject(action, action.ID, conn)
	addObject(data, action, action.ID, conn)
	_, err = conn.Do("EXEC")

	return err
}
1104565
func (s *CreateJobTemplateInput) SetStatusUpdateInterval(v string) *CreateJobTemplateInput {
	s.StatusUpdateInterval = &v
	return s
}
616926
func (s *HealthCheck) SetInterval(v int64) *HealthCheck {
	s.Interval = &v
	return s
}
126157
func (r *Router) IndexHandler(w http.ResponseWriter, _ *http.Request, _ Params) {
	WriteJSON(w, r.Index())
}
336555
func StatusHandler(w http.ResponseWriter, r *http.Request) {
	code, _ := strconv.Atoi(mux.Vars(r)["code"])

	statusWritten := false
	switch code {
	case http.StatusMovedPermanently,
		http.StatusFound,
		http.StatusSeeOther,
		http.StatusUseProxy,
		http.StatusTemporaryRedirect:
		w.Header().Set("Location", "/redirect/1")
	case http.StatusUnauthorized: // 401
		w.Header().Set("WWW-Authenticate", `Basic realm="Fake Realm"`)
	case http.StatusPaymentRequired: // 402
		w.WriteHeader(code)
		statusWritten = true
		io.WriteString(w, "Fuck you, pay me!")
		w.Header().Set("x-more-info", "http://vimeo.com/22053820")
	case http.StatusNotAcceptable: // 406
		w.WriteHeader(code)
		statusWritten = true
		io.WriteString(w, `{"message": "Client did not request a supported media type.", "accept": ["image/webp", "image/svg+xml", "image/jpeg", "image/png", "image/*"]}`)
	case http.StatusTeapot:
		w.WriteHeader(code)
		statusWritten = true
		w.Header().Set("x-more-info", "http://tools.ietf.org/html/rfc2324")
		io.WriteString(w, `
    -=[ teapot ]=-

       _...._
     .'  _ _ '.
    | ."  ^  ". _,
    \_;'"---"'|//
      |       ;/
      \_     _/
        '"""'
`)
	}
	if !statusWritten {
		w.WriteHeader(code)
	}
}