<commit_before>//
//   Copyright 2016  <NAME>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package warp10

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/influxdata/influxdb/client/v2"
	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/outputs"
)

type Warp10 struct {
	Prefix string

	WarpUrl string

	Token string

	Debug bool
}

var sampleConfig = `
  # prefix for metrics class Name
  prefix = "telegraf."
  ## Telnet Mode ##
  # Url name of the Warp 10 server
  warpUrl = "localhost:4242/"
  # Token to access your app on warp 10
  token = "Token"
  # Debug true - Prints Warp communication
  debug = false
`

type MetricLine struct {
	Metric    string
	Timestamp int64
	Value     string
	Tags      string
}

func (o *Warp10) Connect() error {
	// TODO Test Connection to Warp Server

	return nil
}

func (o *Warp10) Write(metrics []telegraf.Metric) error {
	if len(metrics) == 0 {
		return nil
	}
	var timeNow = time.Now()
	collectString := make([]string, len(metrics))
	index := 0
	for _, pt := range metrics {
		metric := &MetricLine{
			Metric:    fmt.Sprintf("%s%s", o.Prefix, pt.Name()),
			Timestamp: timeNow.Unix() * 1000000,
		}

		metricValue, buildError := buildValue(pt.Point())
		if buildError != nil {
			fmt.Printf("Warp: %s\n", buildError.Error())
			continue
		}
		metric.Value = metricValue

		tagsSlice := buildTags(pt.Tags())
		metric.Tags = fmt.Sprint(strings.Join(tagsSlice, ","))

		messageLine := fmt.Sprintf("%v// %s{%s} %v \n", metric.Timestamp, metric.Metric, metric.Tags, metric.Value)
		if o.Debug {
			fmt.Print(messageLine)
		}

		collectString[index] = messageLine
		index += 1
	}
	payload := fmt.Sprint(strings.Join(collectString, "\n"))
	//defer connection.Close()
	req, err := http.NewRequest("POST", o.WarpUrl, bytes.NewBufferString(payload))
	req.Header.Set("X-Warp10-Token", o.Token)
	req.Header.Set("Content-Type", "text/plain")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

	return nil
}

func buildTags(ptTags map[string]string) []string {
	sizeTags := len(ptTags)
	sizeTags += 1
	tags := make([]string, sizeTags)
	index := 0
	for k, v := range ptTags {
		tags[index] = fmt.Sprintf("%s=%s", k, v)
		index += 1
	}
	tags[index] = fmt.Sprintf("source=telegraf")
	sort.Strings(tags)
	return tags
}

func buildValue(pt *client.Point) (string, error) {
	var retv string
	var v = pt.Fields()["value"]
	switch p := v.(type) {
	case int64:
		retv = IntToString(int64(p))
	case string:
		retv = fmt.Sprintf("'%s'", p)
	case bool:
		retv = BoolToString(bool(p))
	case uint64:
		retv = UIntToString(uint64(p))
	case float64:
		retv = FloatToString(float64(p))
	default:
		return retv, fmt.Errorf("unexpected type %T with value %v for Warp", v, v)
	}
	return retv, nil
}

func IntToString(input_num int64) string {
	return strconv.FormatInt(input_num, 10)
}

func BoolToString(input_bool bool) string {<commit_msg>make this work with new metrics<commit_after>//
//   Copyright 2016  <NAME>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package warp10

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/influxdata/influxdb/client/v2"
	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/outputs"
)

type Warp10 struct {
	Prefix string

	WarpUrl string

	Token string

	Debug bool
}

var sampleConfig = `
  # prefix for metrics class Name
  prefix = "telegraf."
  ## Telnet Mode ##
  # Url name of the Warp 10 server
  warpUrl = "localhost:4242/"
  # Token to access your app on warp 10
  token = "Token"
  # Debug true - Prints Warp communication
  debug = false
`

type MetricLine struct {
	Metric    string
	Timestamp int64
	Value     string
	Tags      string
}

func (o *Warp10) Connect() error {
	// TODO Test Connection to Warp Server

	return nil
}

func (o *Warp10) Write(metrics []telegraf.Metric) error {
	if len(metrics) == 0 {
		return nil
	}
	var timeNow = time.Now()
	collectString := make([]string, 0)
	index := 0
	for _, mm := range metrics {

		for k, v := range mm.Fields() {

			metric := &MetricLine{
				Metric:    fmt.Sprintf("%s%s", o.Prefix, mm.Name()+"."+k),
				Timestamp: timeNow.Unix() * 1000000,
			}

			metricValue, buildError := buildValueFromValue(v)
			if buildError != nil {
				fmt.Printf("Warp: %s\n", buildError.Error())
				continue
			}
			metric.Value = metricValue

			tagsSlice := buildTags(mm.Tags())
			metric.Tags = fmt.Sprint(strings.Join(tagsSlice, ","))

			messageLine := fmt.Sprintf("%v// %s{%s} %v \n", metric.Timestamp, metric.Metric, metric.Tags, metric.Value)
			if o.Debug {
				fmt.Print(messageLine)
			}

			collectString = append(collectString, messageLine)
			index += 1
		}
	}
	payload := fmt.Sprint(strings.Join(collectString, "\n"))
	//defer connection.Close()
	req, err := http.NewRequest("POST", o.WarpUrl, bytes.NewBufferString(payload))
	req.Header.Set("X-Warp10-Token", o.Token)
	req.Header.Set("Content-Type", "text/plain")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

	return nil
}

func buildTags(ptTags map[string]string) []string {
	sizeTags := len(ptTags)
	sizeTags += 1
	tags := make([]string, sizeTags)
	index := 0
	for k, v := range ptTags {
		tags[index] = fmt.Sprintf("%s=%s", k, v)
		index += 1
	}
	tags[index] = fmt.Sprintf("source=telegraf")
	sort.Strings(tags)
	return tags
}

func buildValue(pt *client.Point) (string, error) {
	var retv string
	var v = pt.Fields()["value"]
	switch p := v.(type) {
	case int64:
		retv = IntToString(int64(p))
	case string:
		retv = fmt.Sprintf("'%s'", p)
	case bool:
		retv = BoolToString(bool(p))
	case uint64:
		retv = UIntToString(uint64(p))
	case float64:
		retv = FloatToString(float64(p))
	default:
		retv = fmt.Sprintf("'%s'", p)
		//		return retv, fmt.Errorf("unexpected type %T with value %v for Warp", v, v)
	}
	return retv, nil
}

func buildValueFromValue(v interface{}) (string, error) {
	var retv string
	//	fmt.Println("%v", pt.Fields())
	switch p := v.(type) {
	case int64:
		retv = IntToString(int64(p))
	case string:
		retv = fmt.Sprintf("'%s'", p)
	case bool:
		retv = BoolToString(bool(p))
	case uint64:
		retv = UIntToString(uint64(p))
	case float64:
		retv = FloatToString(float64(p))
	default:
		retv = fmt.Sprintf("'%s'", p)
		//		return retv, fmt.Errorf("unexpected type %T with value %v for Warp", v, v)
	}
	return retv, nil
}

func IntToString(input_num int64) string {
	return strconv.FormatInt(input_num, 10)
}

func BoolToString(input_bool bool) string {
{'fraction_non_alphanumeric': 0.14296369965191447, 'fraction_numerical': 0.016036797613127797, 'mean_word_length': 3.644919168591224, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7672685', 'n_tokens_mistral': 3030, 'n_tokens_neox': 2826, 'n_words': 789}