package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	excelize "github.com/xuri/excelize/v2"
	"gitstore.ru/tolikproh/sirius/model"
)

func main() {
	var sirius model.Sirius
	siriusJson, err := ioutil.ReadFile("sirius.json")
	if err != nil {
		fmt.Println("No read file: sirius.json")
		os.Exit(0)
	}

	siriusJson = bytes.TrimPrefix(siriusJson, []byte("\xef\xbb\xbf"))

	if !json.Valid(siriusJson) {
		fmt.Println("Formated file not supported: sirius.json")
		os.Exit(0)
	}

	fmt.Println("Start converted ....")

	err = json.Unmarshal(siriusJson, &sirius)
	if err != nil {
		fmt.Println("Error unmarshal file: sirius.json")
		os.Exit(0)
	}

	if err := SaveToExel("sirius.xlsx", sirius.NewBolid().ZoneInfo()); err != nil {
		fmt.Println("Error create file: sirius.xlsx")
		os.Exit(0)
	}
	fmt.Println("Converted finalise. Create file: sirius.xlsx")
}

func SaveToExel(filename string, data []model.ZoneInfo) error {
	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			return
		}
	}()
	// Create a new sheet.
	f.SetCellValue("Sheet1", "A2", "№ зоны")
	f.SetCellValue("Sheet1", "B2", "Описание зоны")
	f.SetCellValue("Sheet1", "C2", "Адреса в зоне")
	i := 3
	for _, d := range data {
		f.SetCellValue("Sheet1", "A"+strconv.Itoa(i), d.ZoneNum)
		f.SetCellValue("Sheet1", "B"+strconv.Itoa(i), d.ZoneName)
		f.SetCellValue("Sheet1", "C"+strconv.Itoa(i), d.InputString())
		i++
	}
	// Save spreadsheet by the given path.
	if err := f.SaveAs(filename); err != nil {
		return err
	}
	return nil
}
