package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/mattn/go-sqlite3" // Import the SQLite3 driver
	"html/template"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type Icon struct {
	Body  string `json:"body"`
	Width *int   `json:"width,omitempty"`
}

// Define the Root struct to represent the entire JSON structure
type Root struct {
	Prefix string          `json:"prefix"`
	Icons  map[string]Icon `json:"icons"`
	Height int             `json:"height"`
}

func main() {
	outputStr := MakeSvgFiles()
	SaveToSqlite(outputStr)

}

func SaveToSqlite(outputStr string) {
	svgIconDbPath := "./svg-builder/svg_icon.db"
	db, err := sql.Open("sqlite3", svgIconDbPath)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	createTable := `
CREATE TABLE IF NOT EXISTS svg_icon (
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	svg TEXT NOT NULL
);
`
	_, err = db.Exec(createTable)
	if err != nil {
		log.Fatal(err)
	}
	lines := strings.Split(outputStr, "\n")
	insertSql := `
INSERT INTO svg_icon (svg)
VALUES (?)
`
	for _, line := range lines {
		if line == "" {
			continue
		}
		_, err := db.Exec(insertSql, line)
		if err != nil {
			log.Fatal(err)
		}
	}

}

func SaveToTextFile(outputStr string) {
	outputFile := "./output.txt"
	file, err := os.Create(outputFile)
	file.WriteString(outputStr)
	defer file.Close()
	if err != nil {
		log.Print("Error loading JSON file: ", err)
	}
}

func MakeSvgFiles() string {
	jsonFiles, err := GetAllFiles("./svg-builder/json")
	if err != nil {
		log.Fatalf("Error getting JSON files: %v", err)
	}

	if len(jsonFiles) == 0 {
		log.Fatal("No JSON files found in ./json folder")
	}

	var outputStr string
	strSet := make(map[string]struct{})
	for _, filename := range jsonFiles {
		fileData, err := LoadJson(filename)
		if err != nil {
			log.Print("Error loading JSON file: ", err)
			continue
		}
		height := fileData.Height
		for name, icon := range fileData.Icons {

			width := height
			parts := strings.Split(name, "-")
			if len(parts) <= 0 {
				log.Print(name, " has no parts")
				continue
			}
			part0 := parts[0]
			_, exists := strSet[part0]
			if exists {
				continue
			}
			if icon.Width != nil {
				width = *icon.Width
			}
			strSet[part0] = struct{}{}
			if icon.Body == "" {
				continue
			}
			outputStr = fmt.Sprintf("%s<svg  viewBox=\"0 0 %d %d\" xmlns=\"http://www.w3.org/2000/svg\">%s</svg>\n", outputStr, width, height, icon.Body)
		}
	}
	return outputStr
}

func MakeSVGTemplates() {
	// Step 1: Get all JSON files from the ./json folder
	jsonFiles, err := GetAllFiles("./json")
	if err != nil {
		log.Fatalf("Error getting JSON files: %v", err)
	}

	// Check if there are any JSON files found
	if len(jsonFiles) == 0 {
		log.Fatal("No JSON files found in ./json folder")
	}

	// Step 2: Load the first JSON file into a Root struct
	rootData, err := LoadJson(jsonFiles[0])
	if err != nil {
		log.Fatalf("Error loading JSON file: %v", err)
	}

	// Step 3: Load the HTML template from the templates directory
	tmplPath := filepath.Join("templates", "icon_grid.html")
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		log.Fatalf("Error loading template file: %v", err)
	}

	// Step 4: Create an output file for the rendered HTML
	outputFile, err := os.Create("output.html")
	if err != nil {
		log.Fatalf("Error creating output file: %v", err)
	}
	defer outputFile.Close()

	// Step 5: Execute the template with the parsed JSON data and write to the output file
	err = tmpl.Execute(outputFile, rootData)
	if err != nil {
		log.Fatalf("Error rendering template: %v", err)
	}

	fmt.Println("HTML output has been generated successfully: output.html")

}

func GetAllFiles(dir string) ([]string, error) {
	// Use ioutil.ReadDir to list all files in the directory
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, fmt.Errorf("unable to read directory: %v", err)
	}

	// Create a slice to hold the JSON filenames
	var jsonFiles []string

	// Loop through the files and filter out JSON files
	for _, file := range files {
		if !file.IsDir() && filepath.Ext(file.Name()) == ".json" {
			jsonFiles = append(jsonFiles, filepath.Join(dir, file.Name()))
		}
	}

	return jsonFiles, nil
}

func LoadJson(filename string) (*Root, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to read file %s: %v", filename, err)
	}

	var root Root
	err = json.Unmarshal(data, &root)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal JSON: %v", err)
	}

	return &root, nil
}
