package main

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/websocket"
	"github.com/yandex/pandora/core/aggregator/netsample"
)

var (
	id  int = 1
	clients = make(map[int]*websocket.Conn)
)

type (
	Msg struct {
		Tag  string
		Text string
	}
)

func (g *ReadGun) readWS(ammo *Ammo) {
	ws, err := websocket.Dial(fmt.Sprintf("ws://%s/ws", g.conf.Target), "", fmt.Sprintf("http://%s/", g.conf.Target))
	if err != nil {
		fmt.Println("Error dialing to: " + g.conf.Target, err.Error())
		g.reportDuration("readWS", time.Microsecond*505, 505)
	} else {
	    clients[id] = ws
	    id++
		for {
			timenow := time.Now().Unix()
		    if (timenow - shootime) > 3 {
				ws.Close()
				break
			} else {
		        var response = make([]byte, 512)
		        _, err := ws.Read(response)
		        if err != nil {
			        fmt.Printf("Error read websocket %s\n", err.Error())
				}
				
		        params := strings.Split(string(response), "@")
		        startime, err := strconv.ParseInt(params[1], 10, 64)
		        if err != nil {
			        fmt.Printf("Error converting: %s\n", err.Error())
				}
				
			    testime := time.Duration(((time.Now().UnixNano() - startime) / 1000))*time.Microsecond
			    g.reportDuration(params[0], testime, 200)
				outlog.WriteString("Tag: " + params[0] + "\ttime: " + strconv.Itoa(int(testime)) + "\tWSclients count: " + strconv.Itoa(len(clients)) + "\n") 
			}
		}
	}		
}

func (g *WriteGun) writeWS(ammo *Ammo) {
	shootime = time.Now().Unix()
	code := 200
	startime := time.Now().UnixNano()
	message := &Msg{Tag: ammo.Tag, Text: ammo.Tag + "@" + strconv.FormatInt(startime, 10) + "@" + ammo.Text}

	data, err := json.Marshal(message)
	if err != nil {
		fmt.Println(err)
	}

	sample := netsample.Acquire("writeWS")

	ws, err := websocket.Dial(fmt.Sprintf("ws://%s/ws", g.conf.Target), "", fmt.Sprintf("http://%s/", g.conf.Target))	
	if err != nil {
		fmt.Printf("Send failed: %s\n", err.Error())
		code = 314
	}

	_, err = ws.Write([]byte(strconv.Itoa(len(string(data))) + "   " + string(data)))
    if err != nil {
	    fmt.Printf("Send failed: %s\n", err.Error())
		code = 314
	}

	ws.Close()
	defer func () {
		sample.SetProtoCode(code)
		g.aggr.Report(sample)
	}()
}
