/*
 * celbase.cpp - author Matze Braun <MatzeBraun@gmx.de>
 *
 * Copyright (C) 2001 Atomic Blue (info@planeshift.it, http://www.atomicblue.org) 
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation (version 2 of the License)
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */
#include <psconfig.h>

#include <cstool/initapp.h>
#include <csgeom/vector3.h>
#include <ivaria/reporter.h>
#include <ivideo/graph3d.h>
#include <csutil/databuf.h>
#include <iutil/stringarray.h>

#include "engine/celbase.h"
#include "util/consoleout.h"
#include "util/pserror.h"
#include "util/psscf.h"
#include "util/strutil.h"
#include "util/psconst.h"
#include "util/log.h"

#define QUERYPLUG(var, intf, name)        \
    var = CS_QUERY_REGISTRY(object_reg, intf);    \
    if (!var)\
    {                    \
        CPrintf (CON_ERROR, "CelBase: Couldn't find plugin for " name "\n"); \
        return false;                \
    }

CelBase::CelBase()
{
    pl = NULL;    
}

CelBase::~CelBase()
{
    if (pl)
    {
        pl->CleanCache();
        object_reg->Unregister (pl, "iCelPlLayer");
    }
}

static const char* ps_propfactlist[] = {
    "cel.pcfactory.movable",
    "cel.pcfactory.solid",
    "cel.pcfactory.movableconst_cd",
    "cel.pcfactory.gravity",
    "cel.pcfactory.region",
    "cel.pcfactory.defaultcamera",
    "cel.pcfactory.mesh",
    "cel.pcfactory.meshselect",
    "cel.pcfactory.pccommandinput",     
    "cel.pcfactory.linmove",
    "cel.pcfactory.colldet",
    0
};



bool CelBase::Initialize(iObjectRegistry* object_reg)
{
    CelBase::object_reg = object_reg;

    csRef<iGraphics3D> g3d;
    QUERYPLUG (g3d, iGraphics3D, "iGraphics3d");
    if (!g3d)
    {
        CPrintf (CON_ERROR, "CelBase: Couldn't query iGraphics3d\n");
        return false;
    }
    
    txtmgr = g3d->GetTextureManager();
    if (!txtmgr)
    {
        CPrintf (CON_ERROR, "CelBase: Couldn't find texturemanager\n");
        return false;
    }

    QUERYPLUG(engine   ,iEngine       , "iEngine");
    QUERYPLUG(loader   ,iLoader       , "iLoader");
    QUERYPLUG(pluginMgr,iPluginManager, "iPluginManager");
    QUERYPLUG(vfs      ,iVFS          , "iVFS");

    pl = CS_LOAD_PLUGIN(pluginMgr, "cel.physicallayer", iCelPlLayer);
    if (!pl) 
    {
        CPrintf (CON_ERROR, "Couldn't load plugin for PlLayer.\n");
        return false;
    }
    object_reg->Register (pl, "iCelPlLayer");


    // load plugins
    for (const char** pfname=ps_propfactlist; *pfname; pfname++)
    {
        if (!LoadPlugin (*pfname))
            return false;
    }    

    return true;
}

bool CelBase::LoadPlugin (const char* pcfactname)
{
    csRef<iBase> plug = CS_LOAD_PLUGIN_ALWAYS(pluginMgr, pcfactname);
    if (!plug)
    {
        csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
            "planeshift.engine.celbase",
            "CEL '%s' plugin missing!", pcfactname);
        return false;
    }

    return true;
}

// temporary till we have a real resource management design
bool CelBase::LoadTexture (const char* txtName, const char* fileName)
{
    iTextureWrapper* txt = loader->LoadTexture(txtName, fileName,
        CS_TEXTURE_3D, txtmgr, CS_TEXTURE_CREATE_MATERIAL);

    if (!txt)
    {
        csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
            "planeshift.engine.celbase",
            "Error loading texture '%s'!",
            fileName);
        return false;
    }

    pl->Cache (txt);
    iMaterialWrapper* mat = engine->GetMaterialList ()->FindByName (txtName);
    if (mat)
        pl->Cache (mat);
    
    return true;
}


bool CelBase::LoadTextureDir(const char *dir)
{
    csRef<iDataBuffer> xpath = vfs->ExpandPath(dir);
    csRef<iStringArray> files = vfs->FindFiles( **xpath );

    if (!files)
        return false;

    for (size_t i=0; i < files->Length(); i++)
    {
        const char* filename = files->Get(i);
        if (strcmp (filename + strlen(filename) - 4, ".png") && 
            strcmp (filename + strlen(filename) - 4, ".tga") && 
            strcmp (filename + strlen(filename) - 4, ".gif") && 
            strcmp (filename + strlen(filename) - 4, ".bmp") && 
            strcmp (filename + strlen(filename) - 4, ".jpg") &&
            strcmp (filename + strlen(filename) - 4, ".dds"))
            continue;

        // If this is an icon type texture then not required to load as a
        // material. 
        if ( strstr( filename, "_icon" ) )
            continue;
        
        char* name = csStrNew(filename);
        char* onlyname = PS_GetFileName(name);

        if (!LoadTexture(onlyname,filename))
        {
            delete[] name;
            return false;
        }
        delete[] name;
    }
    return true;
}

bool CelBase::LoadTextures()
{
    
    // characters
    if (!LoadTextureDir("/planeshift/models/"))
        return false;

    // Load the textures for the weapons.
    if (!LoadTextureDir("/planeshift/weapons/"))
        return false;

    if (!LoadTextureDir("/planeshift/shields/"))
        return false;
        
    // Load the textures for the items.
    if (!LoadTextureDir("/planeshift/items/"))
        return false;

    // Load the textures for the spell effects
    if (!LoadTextureDir("/planeshift/art/effects/"))
        return false;

    // Load the textures for the resources items
    if (!LoadTextureDir("/planeshift/naturalres/"))
        return false;

    // Load the textures for the tools items
    if (!LoadTextureDir("/planeshift/tools/"))
        return false;

    // Load the textures for the food items
    if (!LoadTextureDir("/planeshift/food/"))
        return false;

    return true;
}

bool CelBase::RemoveActor(iCelEntity *entity)
{
    Debug3(LOG_CELPERSIST,0,"Removing ACTOR: <%s> [%u] from world\n", entity->GetName(), entity->GetID());

    pl->RemoveEntity( entity );
    return true;
}

bool CelBase::RemoveItem( iCelEntity* item )
{
    return RemoveActor(item);
}
