-- Host-side macro demo for Leonardo HID bridge (see script-runner.zip)
local keymap = {
  KEY_LEFT_CTRL = '0x80',
  KEY_LEFT_SHIFT = '0x81',
  KEY_LEFT_ALT = '0x82',
  KEY_LEFT_GUI = '0x83',
  KEY_RIGHT_CTRL = '0x84',
  KEY_RIGHT_SHIFT = '0x85',
  KEY_RIGHT_ALT = '0x86',
  KEY_RIGHT_GUI = '0x87',
  KEY_UP_ARROW = '0xDA',
  KEY_DOWN_ARROW = '0xD9',
  KEY_LEFT_ARROW = '0xD8',
  KEY_RIGHT_ARROW = '0xD7',
  KEY_BACKSPACE = '0xB2',
  KEY_TAB = '0xB3',
  KEY_RETURN = '0xB0',
  KEY_ESC = '0xB1',
  KEY_INSERT = '0xD1',
  KEY_DELETE = '0xD4',
  KEY_PAGE_UP = '0xD3',
  KEY_PAGE_DOWN = '0xD6',
  KEY_HOME = '0xD2',
  KEY_END = '0xD5',
  KEY_CAPS_LOCK = '0xC1',
  KEY_F1 = '0xC2',
  KEY_F2 = '0xC3',
  KEY_F3 = '0xC4',
  KEY_F4 = '0xC5',
  KEY_F5 = '0xC6',
  KEY_F6 = '0xC7',
  KEY_F7 = '0xC8',
  KEY_F8 = '0xC9',
  KEY_F9 = '0xCA',
  KEY_F10 = '0xCB',
  KEY_F11 = '0xCC',
  KEY_F12 = '0xCD',
}

local MOUSE_BUTTONS = { 'left', 'right' }

function this:get_keymap(k)
  return tonumber(keymap[k])
end

function this:click(i)
  self:call('click ' .. MOUSE_BUTTONS[i])
end

local function axis_move(self, delta, axis)
  if delta == 0 then return end
  local n = delta < 0 and -1 or 1
  local remaining = math.abs(delta)
  while remaining > 100 do
    if axis == 'x' then
      self:call('move ' .. (100 * n) .. ' 0 0')
    elseif axis == 'y' then
      self:call('move 0 ' .. (100 * n) .. ' 0')
    else
      self:call('move 0 0 ' .. (100 * n))
    end
    remaining = remaining - 100
  end
  local tail = remaining * n
  if axis == 'x' then
    self:call('move ' .. tail .. ' 0 0')
  elseif axis == 'y' then
    self:call('move 0 ' .. tail .. ' 0')
  else
    self:call('move 0 0 ' .. tail)
  end
end

function this:move(x, y, z)
  axis_move(self, x, 'x')
  axis_move(self, y, 'y')
  axis_move(self, z, 'z')
end

function this:keywrite(c)
  self:call('kwrite ' .. string.byte(c))
end

function this:alt_tab()
  self:call('kpress ' .. self:get_keymap('KEY_LEFT_ALT'))
  self:call('kwrite ' .. self:get_keymap('KEY_TAB'))
  self:call('krelease ' .. self:get_keymap('KEY_LEFT_ALT'))
end

function this:main()
  self:delay(5000)
  for _ = 10, 1, -1 do
    self:move(-1000, -500, 0)
    self:delay(200)
    self:move(540, 260, 0)
    self:delay(300)
    self:call('press left')
    self:delay(100)
    self:move(-224, 140, 0)
    self:delay(100)
    self:call('release left')
    self:delay(500)
    self:call('kwrite ' .. self:get_keymap('KEY_RETURN'))
    self:delay(15000)
  end
end
