local mod_name = minetest.get_current_modname()
local mod_path = minetest.get_modpath(mod_name)
local S = minetest.get_translator(mod_name)

dofile(mod_path .. DIR_DELIM .. "spawning.lua")
dofile(mod_path .. DIR_DELIM .. "rock_projectile.lua")

pmb_kelar = {}
function pmb_kelar.do_sound(self, name, gain)
    minetest.sound_play(("pmb_kelar_"..name), {
        gain = gain or 1,
        pos = self.object:get_pos(),
        object = self.object,
        pitch = (math.random()*0.2) + 0.9
    })
end

local kelar = {
    initial_properties = {
        visual = "mesh",
        mesh = "pmb_kelar.b3d",
        textures = {"pmb_kelar.png"},
        use_texture_alpha = false,
        stepheight = 0.5,
        hp_max = 20,
        physical = true,
        collisionbox = {-0.3, -0.5, -0.3, 0.3, 1, 0.3},
        selectionbox = {-0.3, -0.5, -0.3, 0.3, 1, 0.3},
        pointable = true,
        damage_texture_modifier = "^[colorize:#ff9999:50",
    },
    _name = "pmb_kelar:kelar",


    on_step = pmb_entity_api.do_states(),
    _drop = {
        max_items = 2,
        items = {
            {
                rarity = 4,
                items = {"pmb_items:copper_nugget"},
            },
            {
                rarity = 4,
                items = {"pmb_items:iron_nugget"},
            },
            {
                rarity = 4,
                items = {"pmb_items:tin_nugget"},
            },
            {
                rarity = 4,
                items = {"pmb_stone:cobble"},
            },
        }
    },

    _states = {
        on_step = function(self, dtime, moveresult)
            pmb_entity_api.test_fall_damage(self, dtime, false)
            if not self.object:get_pos() then
                return "die"
            end
            if self._state ~= "death" then
                local in_or_above_water = pmb_entity_api.float_in_liquids(self, dtime * 20, {offset=vector.new(0, 1.2, 0)})
                if not in_or_above_water then
                    pmb_entity_api.apply_gravity(self, dtime)
                end
            end
        end,
        idle = {
            animation = "idle",
            step = function(self, dtime, moveresult)

                pmb_entity_api.get_target(self)
                pmb_entity_api.get_wander(self, 300)
                pmb_entity_api.decelerate(self, 0.8)

                if self._pmb_to_pos and self._pmb_state_time > 1 then
                    if self._pmb_target then
                        return "charge"
                    else
                        return "roam"
                    end
                end
            end,
        },
        roam = {
            animation = "charge",
            on_state_start = function(self)
                if math.random() < 0.5 then
                    local ents = pmb_entity_api.get_objects_of_type(self.object:get_pos(), 80, {"pmb_kelar:kelar"})
                    local try = ents[math.random(1, #ents)]
                    if try then
                        self._pmb_to_pos = try:get_pos()
                    end
                end
                pmb_entity_api.get_path(self)
            end,
            step = function(self, dtime, moveresult)
                local tmp_vel = self.object:get_velocity()
                tmp_vel.y = 0
                if vector.length(tmp_vel) > 0.2 then
                    pmb_entity_api.set_my_animation(self, "charge")
                else
                    pmb_entity_api.set_my_animation(self, "idle")
                end

                pmb_entity_api.get_target(self, nil, {no_to_pos=false})
                if (not self._pmb_to_pos) then
                    pmb_entity_api.get_wander(self, 1)
                    pmb_entity_api.get_path(self)
                end
                pmb_entity_api.do_path(self)
                pmb_entity_api.check_jump(self, 4)

                if not pmb_entity_api.path_reachable(self) then
                    self._pmb_to_pos = nil
                end
                -- no target or target pos
                if (not self._pmb_to_pos) and (not self._pmb_target) then
                    return "idle"
                end

                -- found target, so chase them
                if self._pmb_target then
                    return "charge"
                end

                pmb_entity_api.rotate_to_path(self, dtime*8)
            end,
        },
        charge = {
            on_state_start = function(self)
                if self._pmb_target then
                    self._pmb_time_since_target = 0
                end
            end,
            -- animation = "charge",
            step = function(self, dtime, moveresult)
                if not self._pmb_attack_cooldown then self._pmb_attack_cooldown = 2 end
                if self._pmb_attack_cooldown > 0 then self._pmb_attack_cooldown = self._pmb_attack_cooldown - dtime end
                local dist = pmb_entity_api.get_target_dist(self)

                local tmp_vel = self.object:get_velocity()
                tmp_vel.y = 0
                if vector.length(tmp_vel) > 1 then
                    pmb_entity_api.set_my_animation(self, "charge")
                else
                    pmb_entity_api.set_my_animation(self, "idle")
                end

                if dist and dist > 5 then
                    pmb_entity_api.get_and_follow_target(self, 2.5)
                else
                    pmb_entity_api.get_and_follow_target(self, 1)
                end

                pmb_entity_api.check_jump(self, 4)

                -- no target or target pos
                if (not self._pmb_target) or not dist then
                    return "roam"
                end

                pmb_entity_api.rotate_to_path(self, dtime*3)

                if pmb_entity_api.has_los_to_object(self, self._pmb_target) then
                    pmb_entity_api.punch_in_radius(self, 1, 2.5, {
                        damage_groups = {
                            pierce=2,
                            slash=1,
                        }
                    })
                end

                local has_los
                if self._pmb_target then
                    has_los = pmb_entity_api.has_los_to_object(self, self._pmb_target)
                end

                if (dist and dist > 40 or not has_los) then
                    if self._pmb_time_since_target > 3 then
                        self._pmb_target = nil
                        pmb_entity_api.get_target(self)
                    else
                        self._pmb_time_since_target = self._pmb_time_since_target + dtime
                    end
                end

                if self._pmb_attack_cooldown <= 0 and (dist and dist < 25)
                and pmb_entity_api.has_los_to_object(self, self._pmb_target) then
                    if dist < 7 and math.random() < 0.5 then
                        self._pmb_attack_cooldown = nil
                        return "pre_lunge"
                    elseif dist >= 7 then
                        self._pmb_attack_cooldown = nil
                        return "throw"
                    end
                end
            end,
        },
        throw = {
            animation = "throw",
            on_state_start = function(self)
                local vel = self.object:get_velocity()
                vel.x = 0
                vel.z = 0
                self.object:set_velocity(vel)
                self._pmb_throwing = true
            end,
            step = function(self, dtime, moveresult)
                if not self._pmb_target then
                    pmb_entity_api.get_target(self)
                    if not self._pmb_target then return "charge" end
                end
                pmb_entity_api.rotate_to_target(self, dtime*3)

                if self._pmb_throwing and self._pmb_state_time > (1 / pmb_entity_api.get_current_animation_length(self)) * 30 then repeat
                    self._pmb_throwing = false
                    local pos = vector.offset(self.object:get_pos(), 0, 1, 0)
                    local dir
                    local tpos = self._pmb_target and self._pmb_target:get_pos()
                    tpos.y = tpos.y + 1
                    if tpos then
                        local tvel = self._pmb_target:get_velocity()
                        local dist = vector.distance(pos, tpos)
                        tvel = vector.multiply(tvel, 0.5)

                        tpos = vector.add(tpos, tvel)
                        tpos = vector.offset(tpos,
                            ((math.random() - 0.5) * 2),
                            ((math.random() - 0.5) * 2),
                            ((math.random() - 0.5) * 2))

                        dir = vector.direction(pos, tpos)
                        dir.y = dir.y + 0.20 * (dist / 80) + 0.05
                    else break end

                    local ent = pmb_combat.projectile.add_projectile(self.object,
                        "pmb_kelar:rock_ENTITY",
                        pos, dir, 40
                    )
                    minetest.sound_play(("pmb_whap"), {
                        gain = 1.4,
                        pos = self.object:get_pos(),
                        object = self.object,
                        pitch = (math.random()*0.2) + 0.9,
                        max_hear_distance = 20,
                    })
                until true end

                if self._pmb_state_time > 45 * (1 / pmb_entity_api.get_current_animation_length(self)) then
                    self._pmb_lunge_time = nil
                    return "charge"
                end
            end,
        },
        pre_lunge = {
            animation = "pre_lunge",
            on_state_start = function(self)
                local vel = self.object:get_velocity()
                vel.x = 0
                vel.z = 0
                self.object:set_velocity(vel)
            end,
            step = function(self, dtime, moveresult)
                if not self._pmb_target then
                    pmb_entity_api.get_target(self)
                end
                if not self._pmb_path then
                    pmb_entity_api.get_path(self, pmb_entity_api.min_cost)
                end
                pmb_entity_api.rotate_to_target(self, dtime*3)
                if not self._pmb_lunge_time then self._pmb_lunge_time = 0.5 end
                if self._pmb_lunge_time > 0 then self._pmb_lunge_time = self._pmb_lunge_time - dtime end

                if self._pmb_lunge_time <= 0 then
                    self._pmb_lunge_time = nil
                    return "lunge"
                end
            end,
        },
        lunge = {
            animation = "lunge",
            on_state_start = function(self)
                pmb_kelar.do_sound(self, "lunge_"..(math.random(0,3)), 1)
                self._pmb_path = nil
                self._pmb_to_pos = nil

                if not self._pmb_target then
                    return "idle"
                end
                local target_pos = self._pmb_target:get_pos()
                local pos = self.object:get_pos()
                local dir = vector.direction(pos, target_pos)
                local yaw = minetest.dir_to_yaw(dir)
                self.object:set_yaw(yaw)
                dir = vector.multiply(dir, self._pmb_speed * 1.3)
                dir.y = 4
                self.object:set_velocity(dir)
                self._pmb_lunge_jump = true
            end,
            step = function(self, dtime, moveresult)

                if self._pmb_state_time >= 34 * (1 / pmb_entity_api.get_current_animation_length(self)) then
                    return "charge"
                end

                if self._pmb_lunge_jump and self._pmb_state_time > 3 * (1 / pmb_entity_api.get_current_animation_length(self)) then
                    self._pmb_lunge_jump = false
                    local vel = self.object:get_velocity()
                    self.object:set_velocity(vector.offset(vel, 0, 1.8, 0))
                end

                local dist = pmb_entity_api.get_target_dist(self, 1.5)
                if self._pmb_since_attack >= 1 and dist and dist < 2
                and pmb_entity_api.has_los_to_object(self, self._pmb_target) then
                    self._pmb_target:punch(self.object, 1.0, {
                        full_punch_interval = 1.0,
                        damage_groups = {
                            blunt=4,
                        }
                    }, nil)
                    self._pmb_since_attack = 0
                end
            end,
        },
        death = {
            animation = "death",
            on_state_start = function(self)
                pmb_entity_api.do_drops(self)
                pmb_entity_api.rotate_to_target(self, 1)
                self._pmb_detectable = false
            end,
            step = function(self, dtime, moveresult)
                pmb_entity_api.decelerate(self, 0.2)
                local vel = self.object:get_velocity()
                vel.y = vel.y - self._pmb_gravity * dtime
                self.object:set_velocity(vel)
                if self._pmb_state_time > 1 then
                    local pos = self.object:get_pos()
                    local part = {
                        amount = 10,
                        time = -1,
                        vertical = false,
                        texpool = {
                            "pmb_kelar_particle.png^[multiply:#ccc",
                            "pmb_kelar_particle.png^[multiply:#aaa",
                            "pmb_kelar_particle.png^[multiply:#999",
                        },
                        collisiondetection = true,
                        drag = vector.new(2.5, 0, 2.5),
                        pos = pos,
                        minvel = vector.new(-3, 0.5, -3),
                        maxvel = vector.new( 3, 4,  3),
                        acc = vector.new(0, -9, 0),
                        minexptime = 1,
                        maxexptime = 2,
                        minsize = 0.7,
                        maxsize = 3,
                    }
                    minetest.add_particlespawner(part)
                    self.object:remove()
                end
            end,
        },
    },
    _default_state = "idle",
    on_activate = function(self, staticdata, dtime_s)
        self.object:set_armor_groups({
            pierce=200,
            slash=100,
            blunt=100,
            magic=200,
            poison=100,
        })
        self.object:set_hp(self._pmb_max_health)
        pmb_entity_api.on_activate(self, staticdata, dtime_s)
    end,
    get_staticdata = function(self)
        return pmb_entity_api.get_staticdata(self)
    end,
    on_deactivate = function(self, removal)
        pmb_entity_api.on_deactivate(self, removal)
    end,
    on_punch = function(self, puncher, time_from_last_punch, tool_capabilities, dir, damage)
        if damage and damage > 0 then
            pmb_kelar.do_sound(self, "hurt_0", 1)
            if puncher and puncher ~= self.object and not self._pmb_target then
                self._pmb_target = puncher
                pmb_entity_api.set_state(self, "charge")
            end

            local hp = self.object:get_hp() - damage
            if hp <= 0 then
                pmb_entity_api.set_state(self, "death")
                self.object:set_hp(self._pmb_max_health)
                self.object:set_armor_groups({fleshy=0})
                return true
            end
        end
        return pmb_entity_api.damage.on_punch(self, puncher, time_from_last_punch, tool_capabilities, dir, damage)
    end,
    _pmb_staticdata_load_list = {
        "_pmb_speed",
        "_pmb_damage_groups",
        "_pmb_hostile",
    },
    _pmb_speed = 3,
    _pmb_acceleration = 20,
    _pmb_gravity = 9,
    _pmb_max_health = 20,
    _pmb_detectable = true,
    _pmb_hostile = {player=1},
    _eye_height = 1.3,
    _pmb_damage_groups = {
        pierce=2,
        slash=2,
        blunt=1,
    },
    _animations = {
        idle = {frames={x=0, y=39}, blend=0.2},
        charge = {frames={x=40, y=57}, blend=0.2},
        pre_lunge = {frames={x=110, y=114}, blend=0.2, speed = 24, loop = false},
        lunge = {frames={x=115, y=149}, blend=0.2, speed = 24, loop = false},
        throw = {frames={x=60, y=106}, blend=0.2, speed = 24, loop = false},
        death = {frames={x=150, y=169}, blend=0.2, speed = 24, loop = false},
    },
    _pmb_wander = 3,
    _pmb_range = 20,
    _pmb_statusfx_enable = true,
}


minetest.register_entity("pmb_kelar:kelar", kelar)

local animspeedmult = 0.7
local underkelar = table.copy(kelar)
underkelar.initial_properties.textures = {"pmb_kelar.png^[multiply:#ffb9b780"}
underkelar.initial_properties.glow = 2
underkelar._pmb_speed = underkelar._pmb_speed / animspeedmult
underkelar._pmb_did_variant_check = true
underkelar._drop = {
    max_items = 3,
    items = {
        {
            rarity = 2,
            items = {"pmb_underworld:lava_brick"},
        },
        {
            rarity = 4,
            items = {"pmb_underworld:ash"},
        },
        {
            rarity = 8,
            items = {"pmb_underworld:mythril_strand"},
        },
        {
            rarity = 8,
            items = {"pmb_underworld:mythril_strand 2"},
        },
    }
}
for i, anim in pairs(underkelar._animations) do
    underkelar._animations[i] = table.copy(anim)
    underkelar._animations[i].speed = (underkelar._animations[i].speed or 24) / animspeedmult
end
minetest.register_entity("pmb_kelar:kelar_underworld", underkelar)

minetest.register_craftitem("pmb_kelar:kelar_spawn", {
    description = S("Kelar spawn egg"),
    inventory_image = "pmb_kelar.png",
    on_place = function(itemstack, placer, pointed_thing)
        local ent = minetest.add_entity(vector.offset(minetest.get_pointed_thing_position(pointed_thing), 0, 1, 0), "pmb_kelar:kelar")
    end,
})

minetest.register_craftitem("pmb_kelar:kelar_underworld_spawn", {
    description = S("Kelar Underworld spawn egg"),
    inventory_image = "pmb_kelar.png^[multiply:#ffb9b780",
    on_place = function(itemstack, placer, pointed_thing)
        local ent = minetest.add_entity(vector.offset(minetest.get_pointed_thing_position(pointed_thing), 0, 1, 0), "pmb_kelar:kelar_underworld")
    end,
})

-- get rid of unused vars
underkelar = nil
kelar = nil
