package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
	"os/exec"
	"strings"
	"time"
)

type Plot struct {
	X string `json:"x"`
	Y string `json:"y"`
}

type ChartPlot struct {
	Title  string `json:"title"`
	SizeX  string `json:"x_size"`
	SizeY  string `json:"y_size"`
	LabelX string `json:"x_label"`
	LabelY string `json:"y_label"`
	Plots  []Plot `json:"plots"`
}

var TITLE string = "{TITLE}"
var LABEL_X string = "{LABEL_X}"
var LABEL_Y string = "{LABEL_Y}"
var OUTPUT string = "{OUTPUT}"
var INPUT string = "{INPUT}"
var LINE string = "{LINE}"

func RandString(n int) string {
	rand.Seed(time.Now().UnixNano())
	r := []rune("qwertyuiopasdfghjklzxcvbnm1234567890")
	b := make([]rune, n)
	for i := range b {
		b[i] = r[rand.Intn(len(r))]
	}
	return string(b)
}

func main() {
	filename := "xplot_" + RandString(15)
	chart := ChartPlot{}

	jsonData, errRead := ioutil.ReadFile("./data.json")
	if errRead != nil {
		fmt.Println(errRead.Error())
	}
	err := json.Unmarshal([]byte(string(jsonData)), &chart)
	if err != nil {
		fmt.Println(err.Error())
	}

	f, _ := os.Create(filename + ".data")
	defer f.Close()
	for _, p := range chart.Plots {
		f.WriteString(p.X + " " + p.Y + ",\n")
	}
	f.Sync()

	buf := bytes.NewBuffer(nil)
	tp, _ := os.Open("tp_chart.plot")
	io.Copy(buf, tp)
	defer tp.Close()
	str := string(buf.Bytes())
	str = strings.Replace(str, TITLE, "my Chart", 1)
	str = strings.Replace(str, LABEL_X, "1024", 1)
	str = strings.Replace(str, LABEL_Y, "768", 1)
	str = strings.Replace(str, OUTPUT, filename, 1)
	str = strings.Replace(str, INPUT, filename, 1)
	str = strings.Replace(str, LINE, "donut", 1)

	f2, _ := os.Create(filename + ".plot")
	defer f2.Close()
	f2.WriteString(str)
	f2.Sync()

	out, errOut := exec.Command("./gnuplot", "./"+ filename + ".plot").Output()
	if errOut != nil {
		fmt.Println(errOut.Error())
	}
	fmt.Println(string(out))
}
