package main

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/therecipe/qt/widgets"
)

func enableClimate(i int) {
	temp, err := strconv.ParseFloat(window.ClimateSettingSpinbox.Text(), 64)
	if err != nil {
		showDialogue(true, "Unable to parse temp setting\n%+v", err)
	}
	if guiSettings.GuiTemperatureUnits == "F" {
		temp = (temp - 32) * 5 / 9
	}
	if i == 0 {
		vehicle.StopAirConditioning()
	} else {
		vehicle.SetTemperature(temp, temp)
		vehicle.StartAirConditioning()
	}

	go setValues()
}

func lockDoors(b bool) {
	if b {
		vehicle.UnlockDoors()
	} else {
		vehicle.LockDoors()
	}
	go setValues()
}

func enableCharging(b bool) {
	if b {
		vehicle.StopCharging()
	} else {
		vehicle.StartCharging()
	}
	go setValues()
}

func honkHorn(c bool) {
	err := vehicle.HonkHorn()
	if err != nil {
		showDialogue(true, "There was an error honking the horn\n%+v", err)
		fmt.Printf("%+v\n", err)
	}
	go setValues()
}
func flash(c bool) {
	err := vehicle.FlashLights()
	if err != nil {
		showDialogue(true, "There was an error flashing the lights\n%+v", err)
		fmt.Printf("%+v\n", err)
	}
	go setValues()
}
func openTrunk(c bool) {
	err := vehicle.OpenTrunk("rear")
	if err != nil {
		showDialogue(true, "There was an error opening your trunk\n%+v", err)
		fmt.Printf("%+v\n", err)
	}
	go setValues()
}
func openFrunk(c bool) {
	err := vehicle.OpenTrunk("front")
	if err != nil {
		showDialogue(true, "There was an error opening your frunk\n%+v", err)
		fmt.Printf("%+v\n", err)
	}
	go setValues()
}

func showDialogue(recover bool, msg string, a ...interface{}) {
	popup = true
	if !recover {
		window.Close()
	}
	dialogue := widgets.NewQDialog(nil, 0)
	centralWidget := widgets.NewQWidget(dialogue, 0)
	actionHBox := widgets.NewQHBoxLayout()
	formLayout := widgets.NewQFormLayout(nil)
	contBtn := widgets.NewQPushButton(nil)
	quitBtn := widgets.NewQPushButton(nil)
	message := widgets.NewQLabel(nil, 0)

	dialogue.SetWindowTitle("TeslaGo Alert")
	dialogue.SetMinimumWidth(255)
	dialogue.SetMinimumHeight(50 + (20 * (1 + strings.Count(msg, "\n"))))

	contBtn.SetText("Continue")
	quitBtn.SetText("Quit")
	message.SetText(fmt.Sprintf(msg, a...))
	message.SetWordWrap(true)

	contBtn.ConnectClicked(func(checked bool) {
		window.Show()
		popup = false
		dialogue.Close()

		go setValues()
	})
	quitBtn.ConnectClicked(func(checked bool) {
		mainApp.Quit()
	})

	if recover {
		actionHBox.AddWidget(contBtn, 0, 0)
	}
	actionHBox.AddWidget(quitBtn, 0, 0)

	formLayout.AddRow5(message)
	formLayout.AddRow6(actionHBox)
	centralWidget.SetLayout(formLayout)

	dialogue.Show()
}

func formatDuration(d time.Duration) string {
	d = d.Round(time.Minute)
	h := d / time.Hour
	d -= h * time.Hour
	m := d / time.Minute
	return fmt.Sprintf("%02dh%02dm", h, m)
}