/*

--------
|SKRUZD|
--------

The MIT License

Copyright (c) 2006 Inko Illarramendi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/


#include <crystalspace.h>

#include <celtool/initapp.h>
#include <propclass/zone.h>
#include <propclass/camera.h>
#include <propclass/mesh.h>
#include <propclass/linmove.h>
#include <propclass/actormove.h>
#include <propclass/input.h>
#include <physicallayer/propclas.h>
#include <propclass/tooltip.h>
#include <propclass/solid.h>
#include <propclass/spawn.h>
#include <propclass/region.h>
#include <propclass/timer.h>
#include <propclass/mover.h>
#include <propclass/prop.h>


#include <physicallayer/entity.h>
#include <physicallayer/propclas.h>
#include <propclass/linmove.h>
#include <propclass/prop.h>
#include <propclass/trigger.h>
#include <propclass/region.h>

#include <propclass/tooltip.h>
#include <propclass/timer.h>
#include <propclass/move.h>
#include <propclass/input.h>
#include <propclass/spawn.h>
#include <propclass/solid.h>
#include <propclass/colldet.h>

#include "behave.h"
#include "bspawner.h"

BehaviourSpawner::BehaviourSpawner (iCelEntity* entity, BehaviourLayer* bl, iCelPlLayer* pl)
        : BehaviourCommon (entity, bl, pl, app)
{

    id_pctimer_wakeup = pl->FetchStringID ("pctimer_wakeup");
    id_pcspawn_newentity = pl->FetchStringID ("pcspawn_newentity");
}

bool BehaviourSpawner::SendMessage (csStringID msg_id,
                                    iCelPropertyClass* pc,
                                    celData& ret, iCelParameterBlock* params, va_list arg)
{
    /// The iPcSpawn property sends an message to this beaviour telling
    ///that the new entity has been created, so we will create properties
    ///for this entity and put it in game.
    /// Also, each period of time it will check the killed enemies to
    ///respawn them.

    csRef<iCelEntityList> entitylist= pl-> CreateEmptyEntityList ();
    csRef<iCelEntity> bad_entity;
    bad_entity = pc-> GetEntity();

    if (msg_id == id_pcspawn_newentity)
    {//new entity has been created, so we add properties to it and we put it on game

        csRef<iPcSpawn> pcspawn = CEL_QUERY_PROPCLASS_ENT (
                                      bad_entity, iPcSpawn);

        //we take the new entity and we add properties to it, setting the model
        iCelEntity* new_entity = pl->FindEntity ("spawn");
        csRef<iPcMesh> pcmesh = CEL_QUERY_PROPCLASS_ENT (
                                    new_entity, iPcMesh);
        //we change the name to the entity
        new_entity->SetName("bad2");
        //set the model
        pcmesh->SetPath ("/this/model");
        pcmesh->SetMesh ("ant", "ant.cfg");
        //pcmesh-> SetMesh ("box", "box");
        if (!pcmesh->GetMesh ())
            printf("Error loading model!");

        //We create the iPcLinearMovement
        pl->CreatePropertyClass (new_entity, "pclinearmovement");
        csRef<iPcLinearMovement> pclinmove = CEL_QUERY_PROPCLASS_ENT (
                                                 new_entity, iPcLinearMovement);
        pclinmove->InitCD (
            csVector3 (0.5, 0.25,0.5),
            csVector3 (0.5,0.25,0.5),
            csVector3 (0,0,0));

        // Get the sector to set the position.
        iCelEntity* level_entity = pl->FindEntity ("level");
        csRef<iPcRegion> pcregion = CEL_QUERY_PROPCLASS_ENT (
                                        level_entity, iPcRegion);
        iSector* sector = pcregion->FindSector ("Scene");

        // Random number for the 4 positions in the map to spawn. Depending the number, new pos.
        int spawnpos = (rand() % 4) + 1;
        switch(spawnpos)
        {
            case 1:
            pclinmove->   SetPosition(csVector3 (97,-20,97), 6.28f, sector);
            break;
            case 2:
            pclinmove-> SetPosition(csVector3 (-105,-20,88), 6.28f, sector);
            break;
            case 3:
            pclinmove-> SetPosition(csVector3 (-105,-10,-110), 6.28f, sector);
            break;
            default:
            pclinmove-> SetPosition(csVector3 (110,5,-110), 6.28f, sector);
        };

        // Create the iPcActorMove property to move the entity.
        pc = pl->CreatePropertyClass (new_entity, "pcactormove");
        csRef<iPcActorMove> pcactormove = CEL_QUERY_PROPCLASS_ENT (
                                              new_entity, iPcActorMove);
        pcactormove->  SetMovementSpeed (3);
        pcactormove-> Forward(true);

        // The procedure to create a collider box, to make solid animated characters
        csRef<iCollideSystem> cd_sys = CS_QUERY_REGISTRY ((iObjectRegistry*)*app,
                                       iCollideSystem);
        iMeshWrapper* mesh = pcmesh -> GetMesh();
        csBox3 box (-0.5, 0, -0.5, 0.5, 0.5, 0.5);
        csPolygonMeshBox* pmbox = new csPolygonMeshBox (box);
        // Set the mesh with the collider box
        csColliderWrapper* wrapper = new csColliderWrapper (
                                         mesh->QueryObject (), cd_sys, pmbox);
        pmbox->DecRef ();
        wrapper->DecRef ();

        // Create the iPcTimer to control the enemy's A.I.
        pl->CreatePropertyClass (new_entity, "pctimer");
        csRef<iPcTimer> pctimer = CEL_QUERY_PROPCLASS_ENT (
                                      new_entity, iPcTimer);
        pctimer->WakeUp(500,true);

        return true;
    }//new_entity

    if (msg_id == id_pctimer_wakeup)
    {
        // Check for an invisible (killed) entity and put it in game

        size_t listcount= pl->GetEntityCount ();
        if (listcount>0)
        {
            const char* name;
            size_t i;
            for (i=0;i<listcount;i++)
            {
                iCelEntity * entity;
                entity = pl-> GetEntityByIndex (i);
                csRef<iPcMesh> pcmesh = CEL_QUERY_PROPCLASS_ENT (
                                            entity, iPcMesh);

                name=entity->GetName();
                //check if it is an enemy and not visible
                if ((!strcmp (name, "bad2")) && !(pcmesh-> IsVisible()))
                {
                    // Get the sector
                    iCelEntity* level_entity = pl->FindEntity ("level");
                    csRef<iPcRegion> pcregion = CEL_QUERY_PROPCLASS_ENT (
                                                    level_entity, iPcRegion);
                    iSector* sector = pcregion->FindSector ("Scene");

                    // Get the iPcLinearMovement to set the position
                    csRef<iPcLinearMovement> pclinmove = CEL_QUERY_PROPCLASS_ENT (
                                                             entity, iPcLinearMovement);

                    // random number for the 4 positions in the map to spawn. Depending the number, new pos.
                    int spawnpos = (rand() % 4) + 1;
                    switch(spawnpos)
                    {
                        case 1:
                        pclinmove->   SetPosition(csVector3 (97,-20,97), 6.28f, sector);
                        break;
                        case 2:
                        pclinmove-> SetPosition(csVector3 (-105,-20,88), 6.28f, sector);
                        break;
                        case 3:
                        pclinmove-> SetPosition(csVector3 (-105,-10,-110), 6.28f, sector);
                        break;
                        default:
                        pclinmove-> SetPosition(csVector3 (110,5,-110), 6.28f, sector);
                    };
                    pcmesh-> Show();
                    break;//if we have found one, we exit the loop.
                }
            }//for
        }
        return true;
    }

    return BehaviourCommon::SendMessage (msg_id, pc, ret, params, arg);

}
