RunOncePath("lib/flap_control").
RunOncePath("lib/stabilize_aircraft").
RunOncePath("lib/ui").

clearguis().

global done is false.
on AG9 {
  set done to true.
  return true.
}

function landingMode {
  print "Setting flaps to landing mode.".
  SetFlapAngle(20).
  when SHIP:VELOCITY:SURFACE:MAG < 0.1 then {
    takeoffMode().
  }
}

function takeoffMode {
  print "Setting flaps to takeoff mode.".
  SetFlapAngle(10).
  on GEAR {
    if GEAR = true {
      return true.
    }
    landingMode().
  }
}

if SHIP:STATUS = "LANDED" or SHIP:STATUS = "PRELAUNCH" {
  takeoffMode().
} else {
  landingMode().
}

// Top-level elements.
local iface is gui(250, 300).
set iface:X to 200.
set iface:Y to 700.
local top is iface:AddVLayout().
local rows is List(MakeRow(top), MakeRow(top)).
local stk is iface:AddStack().

AddStockButtons(rows[0], "aircraft").

// rows[0]:AddLabel("FLAPS").
// // Todo: make angles configurable...
// set rows[1]:AddButton("Takeoff"):onClick to {
//   SetFlapAngle(10).
// }.

// set rows[1]:AddButton("Land"):onClick to {
//   SetFlapAngle(20).
// }.

// set rows[2]:AddButton("Extend"):onClick to {
//   SetFlaps(true).
// }.

// set rows[2]:AddButton("Retract"):onClick to {
//   SetFlaps(true).
// }.

// rows[3]:AddLabel("AUTO").

MakeMenu(
  stk,
  MakeButton(rows[1], "Level"),
  List(
    List("Kp", "SCALAR", "0.02"),
    List("Ki", "SCALAR", "0.01"),
    List("Kd", "SCALAR", "1")
  ),
  "Execute",
  {
    parameter options.
    HoldHorizon(
      options["Kp"]:TEXT:ToNumber(),
      options["Ki"]:TEXT:ToNumber(),
      options["Kd"]:TEXT:ToNumber()
    ).
  }
).


iface:show().

wait until false.