package main

import (
	"embed"
	"encoding/csv"
	"os"

	"git.cems.dev/cdricms/bdooc/parsing"
	p "git.cems.dev/cdricms/bdooc/proto"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/menu"
	"github.com/wailsapp/wails/v2/pkg/menu/keys"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {
	// Create an instance of the app structure
	app := NewApp()
  appMenu := menu.NewMenu()
  fileMenu := appMenu.AddSubmenu("File")
  fileMenu.AddText("Open proto file", keys.CmdOrCtrl("o"), func(_ *menu.CallbackData) {
    path := app.GetProtoPath()
    runtime.EventsEmit(app.ctx, "proto-opened", path)
  })

  fileMenu.AddText("Convert CSV to Proto", keys.CmdOrCtrl("k"), func(_ *menu.CallbackData) {
    path := app.OpenPath([]runtime.FileFilter{{
      DisplayName: "CSV file",
      Pattern: "*.csv",      
    }}) 

    employeesProtoChan := make(chan *p.EmployeeList)

    go func() {
      // Parse CSV to Go Struct
      file, err := os.Open(path)
      if err != nil {
        panic(err)
      }
      defer file.Close()
      reader := csv.NewReader(file) 
      employees, err := parsing.UnmarshalEmployees(reader)
      if err != nil {
        panic(err)
      }
      // Convert CSV's Go struct to Proto
      employeesProto := parsing.MapToProto(employees)
      employeesProtoChan <- employeesProto
    }()

    // Get the filepath from the user.
    filePath, err := runtime.SaveFileDialog(app.ctx, runtime.SaveDialogOptions{
      Title: "Destination for Proto file.",
      Filters: []runtime.FileFilter{{
        DisplayName: "Proto binary file",
        Pattern: "*.bin",
      }},
    })
    if err != nil {
      panic(err)
    }
    // Await the conversion
    employeesProto := <-employeesProtoChan
    // Save
    employeesProto.SaveToFile(filePath)
    runtime.EventsEmit(app.ctx, "csv-converted", filePath)
  })

  analysisMenu :=appMenu.AddSubmenu("Analysis")
  analysisMenu.AddText("Aggregation", keys.CmdOrCtrl("a"), func(_ *menu.CallbackData) {
    runtime.EventsEmit(app.ctx, "aggregation")
  })

	// Create application with options
	err := wails.Run(&options.App{
		Title:  "bdooc-t",
		Width:  1024,
		Height: 768,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
    Menu: appMenu,
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}
