package main

import (
	"fmt"
	"log"
	"net/http"

	"gitlab.com/pactual1/backend/config"
	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/routes"
	"gitlab.com/pactual1/backend/shared"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/qor/admin"
)

var DB *gorm.DB

func main() {


	// LOAD APPLICATION CONFIGURATION
	err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	// Db Connect and Close
	if err := shared.Init(); err != nil {
		log.Fatalf("Failed to initialize shared resources: %v", err)
	}
	defer shared.CloseDb()

	// Initialize Admin interface
	Admin := admin.New(&admin.AdminConfig{DB: shared.GetDb()})
	Admin.RegisterViewPath("app/views/qor")
	fmt.Printf("Admin instance: %+v\n", Admin)
	// Allow Admin to manage User resource
	company := Admin.AddResource(&models.Company{})
	company.Meta(&admin.Meta{Name: "Users", Config: &admin.SelectManyConfig{SelectMode: "bottom_sheet"}})
	company.Meta(&admin.Meta{Name: "Devices", Config: &admin.SelectManyConfig{SelectMode: "bottom_sheet"}})
	
	// Add User and Device resources
	Admin.AddResource(&models.User{})
	Admin.AddResource(&models.Device{})
	// Initialize HTTP request multiplexer
	mux := http.NewServeMux()
	// Mount admin interface to mux
	Admin.MountTo("/admin", mux)

	// Start the admin server in a separate goroutine
	go func() {
		port :=  config.AppConfig.Service.Port
		fmt.Println("Admin server listening on :" + port)
		http.ListenAndServe(":" + port, mux)
	}()

	// Initialize Gin
	r := gin.Default()
	routes.InitRouter(r)
	// Start the Gin server on another port
	port :=  config.AppConfig.AdminService.Port
	fmt.Println("Application server listening on :" + port)
	r.Run(":" + port)

}
