package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"

	"github.com/xuri/excelize/v2"
)

// Initial concept from https://stackoverflow.com/q/68621039

var end = errors.New("invalid end of array or object")

func main() {
	file, err := ioutil.ReadFile("test.json")
	if err != nil {
		panic(err)
	}

	testkey, err := objectKeys([]byte(file))
	fmt.Println(testkey, err)
	return

	var data interface{}
	json.Unmarshal(file, &data) // reading all json data
	//fmt.Println(data)
	t, ok := data.([]interface{}) // assertion Interface
	_ = ok
	//fmt.Printf("%[1]v  %[1]T\n", t) //map[string]interface {}

	myMap := t[0] // aim here to get APP, Company and Category which will be the column name of Excel sheet
	fmt.Printf("myMap: %v\n", myMap)
	columnData, _ := myMap.(map[string]interface{}) // extract the underlying concrete data from interface
	fmt.Printf("columnData: %v\n", columnData)
	keys := make([]string, 0, len(columnData)) // creating and initializing slice to store column
	for k := range columnData {
		fmt.Printf("%[1]v %[1]T\n", k)
		keys = append(keys, k)
	}

	return

	xlsx := excelize.NewFile()
	sheetName := "Sheet1"
	xlsx.SetSheetName(xlsx.GetSheetName(1), sheetName)
	c := 'A'
	asciiValue := int(c)
	var a string
	for i := 0; i < len(keys); i++ {
		a = string(asciiValue)
		xlsx.SetCellValue(sheetName, a+"1", keys[i])
		asciiValue++
	}
	err = xlsx.SaveAs("./Onkar.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Excel file generated sucessfully")
}

func objectKeys(b []byte) ([]string, error) {
	d := json.NewDecoder(bytes.NewReader(b))
	t, err := d.Token()
	if err != nil {
		return nil, err
	}
	if t != json.Delim('{') {
		return nil, errors.New("expected start of object")
	}
	var keys []string
	for {
		t, err := d.Token()
		if err != nil {
			return nil, err
		}
		if t == json.Delim('}') {
			return keys, nil
		}
		keys = append(keys, t.(string))
		if err := skipValue(d); err != nil {
			return nil, err
		}
	}
}
func skipValue(d *json.Decoder) error {
	t, err := d.Token()
	if err != nil {
		return err
	}
	switch t {
	case json.Delim('['), json.Delim('{'):
		for {
			if err := skipValue(d); err != nil {
				if err == end {
					break
				}
				return err
			}
		}
	case json.Delim(']'), json.Delim('}'):
		return end
	}
	return nil
}
