# bfdil main control

namespace eval bfdil {
}

proc stdConfig::bfdil {} {
  variable name
  variable path
  variable node
  variable ctrl
  
  variable hostport none
  controller syncedprot 30

  obj bfdil -drive wr
  prop layoutpos -10
  prop label set
  if {[info proc stdConfig::tdrive] eq ""} {
    namespace eval :: {
      source drivers/trun.tcl
    }
  }
  kids "main dilution control" {

    node heatcontrol -int out
    default 0
    prop label "heater/control on "
    prop enum mc/mc,mc/rod,rod/rod
    prop check bfdil::check_heatcontrol
    prop write stdSct::completeUpdate

    node control -int out
    default 0
    prop label "control "
    prop enum off,on
    prop check bfdil::check_control
    prop write stdSct::completeUpdate

  }

  tdrive "main dilution control" -log 1
  hsetprop $path/set check bfdil::check_set
  hsetprop $path/set visible false

  hset $name/control 0
  $ctrl updatescript /tlmc bfdil::updateIfSelected
  hsetprop /tlmc update0 1
  $ctrl updatescript /tlrod bfdil::updateIfSelected
  hsetprop /tlrod update1 1
  hsetprop /tlrod update2 1
}

proc bfdil::check_set {} {
  sct update [sct target]
  switch -- [hvali [sct parent]/heatcontrol] {
    0 {
      set tl tlmc
    }
    1 - 2 {
      set tl tlrod
    }
  }
  if {[sct target]} {
    $tl set [sct target]
    hupdate [sct parent]/control 1
  } else {
    $tl mode 0
    hupdate [sct parent]/control 0
  }
}

proc bfdil::check_heatcontrol {} {
  sct update [sct target]
  switch -- [sct target] {
    0 {
      tlrod mode 0
      tlmc outvar mchtr
    }
    1 {
      tlmc mode 0
      tlrod outvar mchtr
    }
    2 {
      tlmc mode 0
      tlrod outvar rodhtr
    }
  }
}

proc bfdil::check_control {} {
  sct update [sct target]
  if {[hvali [sct parent]/heatcontrol] == 0} {
    set tl tlmc
  } else {
    set tl tlrod
  }
  catch {
    $tl mode [sct target]
  }
}

proc bfdil::updateIfSelected {bfdilpath value} {
  if {[silent 0 sct update[hvali $bfdilpath/heatcontrol]]} {
    set e [silent 0 sct geterror]
    if {$e eq "0"} {
      updateval $bfdilpath $value
      hsetprop $bfdilpath updatetime [clock seconds]
    } else {
      updateerror $bfdilpath $e 1
    }
  }
}


