var dt       = 0 ;
var isFiring = 0;

var targetingGround = func {
  var myGroundTarget = groud_target.new();
  myGroundTarget.init();
}

#This object create an AI object where is the last click
var groud_target = {

  new : func () {
    var m = { parents : [groud_target] };
    m.coord = geo.Coord.new();

    # Find the next index for "models/model" and create property node.
    # Find the next index for "ai/models/trolley" and create property node.
    # (M. Franz, see Nasal/tanker.nas)
    var n = props.globals.getNode("models", 1);
    for (var i = 0; 1; i += 1) {
      if (n.getChild("model", i, 0) == nil) {
        break;
      }
      m.model = n.getChild("model", i, 1);
    }
    #print("m.model :" ~ m.model);

    var n = props.globals.getNode("ai/models", 1);
    for (var i = 0; 1; i += 1) {
      if (n.getChild("trolley", i, 0) == nil) {
        break;
      }
      m.ai = n.getChild("trolley", i, 1);
    }
    #print("m.ai :" ~ m.ai);

    m.ai.getNode("valid", 1).setBoolValue(1);

    m.id_model = "Models/Trolley/trolley.xml";

    m.life_time = 0;

    m.life_time = 600;
    m.altAdjustment = 0;

    m.id = m.ai.getNode("id",1);
    m.callsign = m.ai.getNode("callsign",1);

    m.lat             = m.ai.getNode("position/latitude-deg", 1);
    m.long            = m.ai.getNode("position/longitude-deg", 1);
    m.alt             = m.ai.getNode("position/altitude-ft", 1);

    m.hdgN            = m.ai.getNode("orientation/true-heading-deg", 1);
    m.pitchN          = m.ai.getNode("orientation/pitch-deg", 1);
    m.rollN           = m.ai.getNode("orientation/roll-deg", 1);

    m.radarRangeNM    = m.ai.getNode("radar/range-nm", 1);
    m.radarbearingdeg = m.ai.getNode("radar/bearing-deg", 1);
    m.radarInRange    = m.ai.getNode("radar/in-range", 1);
    m.elevN           = m.ai.getNode("radar/elevation-deg", 1);
    m.hOffsetN        = m.ai.getNode("radar/h-offset", 1);
    m.vOffsetN        = m.ai.getNode("radar/v-offset", 1);

    #Speed
    m.ktasN           = m.ai.getNode("velocities/true-airspeed-kt", 1);
    m.vertN           = m.ai.getNode("velocities/vertical-speed-fps", 1);

    #Time management
    m.lasTime         = 0;
    m.Time            = 0;

    return m;
  },

  del: func {
    me.model.remove();
    me.ai.remove();
  },

  init : func() {
    me.coord = geo.aircraft_position();
    #me.coord = geo.click_position();

    var tempLat = me.coord.lat();
    var tempLon = me.coord.lon();
    var tempAlt = me.coord.alt() ;
    me.altAdjustment = me.coord.alt() - geo.elevation(tempLat,tempLon);
    #print("My adjustement :" ~ me.altAdjustment);

    var myheading = getprop("/orientation/heading-deg");
    var mypitch = getprop("/orientation/pitch-deg");
    var myroll = getprop("/orientation/roll-deg");
    var myspeed = getprop("/velocities/groundspeed-kt");

    # There must be value in it
    me.lat.setValue(tempLat);
    me.long.setValue(tempLon);
    me.alt.setValue(tempAlt*M2FT);

    me.callsign.setValue("TROLLEY");
    me.id.setValue(-2);
    me.hdgN.setValue(myheading);
    me.pitchN.setValue(mypitch);
    me.rollN.setValue(myroll);
    me.radarRangeNM.setValue(10);
    me.radarbearingdeg.setValue(0);
    me.radarInRange.setBoolValue(1);
    me.elevN.setValue(0);
    me.hOffsetN.setValue(0);
    me.vOffsetN.setValue(0);
    me.ktasN.setValue(myspeed);
    me.vertN.setValue(0);

    #Put value in model
    #Beware : No absolute value here but the way to find the property
    me.model.getNode("path", 1).setValue(me.id_model);
    me.model.getNode("latitude-deg-prop", 1).setValue(me.lat.getPath());
    me.model.getNode("longitude-deg-prop", 1).setValue(me.long.getPath());
    me.model.getNode("elevation-ft-prop", 1).setValue(me.alt.getPath());
    me.model.getNode("heading-deg-prop", 1).setValue(me.hdgN.getPath());
    me.model.getNode("pitch-deg-prop", 1).setValue(me.pitchN.getPath());
    me.model.getNode("roll-deg-prop", 1).setValue(me.rollN.getPath());
    me.model.getNode("load", 1).remove();

    #Show of the gear
    setprop("/controls/gear/show-trolley",0);

    me.update();
    settimer(func me.del(), me.life_time);

  },

  update : func(){
    #We Update the time to calcul the interval, multiply it by speed, and obtain a distance that will feed geo.apply_course_distance
    me.Time  = getprop("sim/time/elapsed-sec");
    var interval = me.Time - me.lasTime;
    if (interval>1) {
      interval=0;
    }

    #Update me.coord : Could be a selectionnable option. The goal should to select multiple ground target
    #The trolley.xml, is a - 1 m 3D object, initialy made for the aircaft itself. Do we have to put a + 1 to the altitude The ideal would ask Manu to put it at 0 m
    #me.coord = geo.click_position();

    #Setting Speed
    var speedKMH = (me.ktasN.getValue() * 1.852)-(10*interval); #1 is how to slow down...not very "real"
    if (speedKMH<0) {
      speedKMH=0;
    }

    #Setting Distance in meters (speed in transformed from km/h in m/s
    var myDistance =  interval  * (speedKMH *1000 /3600);

    #Update position
    #var myCoord = geo.Coord.new(me.coord);
    me.coord.apply_course_distance(me.hdgN.getValue(),myDistance);

    #Update Position of the Object
    var tempLat = me.coord.lat();
    var tempLon = me.coord.lon();

    #Altitude
    me.coord.set_alt(geo.elevation(tempLat,tempLon));
    var tempAlt = me.coord.alt() + me.altAdjustment;

    #Pitch calculation
    #FrontAlt
    var myCoordFront = geo.Coord.new(me.coord);
    myCoordFront.apply_course_distance(me.hdgN.getValue(),2);
    var FrontAlt = geo.elevation(myCoordFront.lat(),myCoordFront.lon()) + me.altAdjustment;
    #RearAlt
    var myCoordRear = geo.Coord.new(me.coord);
    myCoordRear.apply_course_distance(me.hdgN.getValue(),- 2);
    var RearAlt = geo.elevation(myCoordRear.lat(),myCoordRear.lon()) + me.altAdjustment;
    #Basic trigo to set up the pitch
    var myPitch = math.atan2((FrontAlt - RearAlt),4)* R2D;

    #print("Pitch:" ~ math.atan2((FrontAlt - RearAlt),4)* R2D);
    #print("speed in KM/h : " ~me.ktasN.getValue() * 1.852);
    #print("Theorical Distance :" ~ myDistance);
    #print("What it is now :" ~ me.coord.distance_to(myCoord));

    me.lat.setValue(tempLat);
    me.long.setValue(tempLon);
    me.alt.setValue(tempAlt*M2FT);
    me.pitchN.setValue(myPitch);

    #Update Distance to aircaft
    me.ac = geo.aircraft_position();
    var alt = me.coord.alt();
    me.distance = me.ac.distance_to(me.coord);

    #Set the Speed
    me.ktasN.setValue(speedKMH/1.852);

    #Update bearing
    me.bearing = me.ac.course_to(me.coord);

    #Update Radar Stuff
    var dalt = alt - me.ac.alt();
    var ac_hdg = getprop("/orientation/heading-deg");
    var ac_pitch = getprop("/orientation/pitch-deg");
    var ac_contact_dist = getprop("/systems/refuel/contact-radius-m");
    var elev = math.atan2(dalt, me.distance) * R2D;

    me.radarRangeNM.setValue(me.distance * M2NM);
    me.radarbearingdeg.setValue(me.bearing);
    me.elevN.setDoubleValue(elev);
    me.hOffsetN.setDoubleValue(view.normdeg(me.bearing - ac_hdg));
    me.vOffsetN.setDoubleValue(view.normdeg(elev - ac_pitch));

    #Put Time in Last Time
    me.lasTime = me.Time;
    settimer(func me.update(), 0);
  }
};

var InitListener = setlistener("/gear/gear[2]/wow", func {
  if (getprop("position/gear-agl-ft") > 0.1) {
    #print("Object Creation, time=" ~ getprop("sim/time/elapsed-sec"));
    settimer(targetingGround, 0);
    removelistener(InitListener);
    setprop("/controls/gear/gear-down",0);
  }
});
