local map = ...
local game = map:get_game()

function map:on_started()

  ice:set_modified_ground("ice")
end

function map:on_opening_transition_finished()

  game:set_ability("sword", 1)
  game:set_ability("sword_spin_attack", 1)
  assert_equal(hero:get_ground_below(), "ice")

  local start_direction = hero:get_direction()
  local start_x, start_y = hero:get_position()

  -- Start loading the spin attack, then try to change direction while
  -- still holding the attack command.
  game:simulate_command_pressed("attack")
  hero:start_attack_loading(0)
  assert_equal(hero:get_state(), "sword loading")
  game:simulate_command_pressed("down")

  sol.timer.start(map, 500, function()

    -- Bug #1: the hero should still be able to slide on the ice while
    -- loading, but its facing direction must stay locked.
    assert_equal(hero:get_state(), "sword loading")
    assert_equal(hero:get_direction(), start_direction)

    local loading_x, loading_y = hero:get_position()
    assert(loading_x ~= start_x or loading_y ~= start_y)

    -- Release the attack command: the sword was already loaded, so a
    -- spin attack starts.
    game:simulate_command_released("attack")

    later(function()
      assert_equal(hero:get_state(), "sword spin attack")

      local spin_direction = hero:get_direction()
      local spin_x, spin_y = hero:get_position()

      -- Try to change direction during the spin attack animation.
      game:simulate_command_released("down")
      game:simulate_command_pressed("up")

      sol.timer.start(map, 200, function()

        -- Bug #2: the hero must not move nor restart the spin attack
        -- animation because of a direction change while on ice.
        assert_equal(hero:get_state(), "sword spin attack")
        assert_equal(hero:get_direction(), spin_direction)

        local now_x, now_y = hero:get_position()
        assert_equal(now_x, spin_x)
        assert_equal(now_y, spin_y)

        game:simulate_command_released("up")

        sol.timer.start(map, 400, function()
          assert_equal(hero:get_state(), "free")
          sol.main.exit()
        end)
      end)
    end)
  end)
end
