
#include <Spectre/System/Path.h>
#include <Spectre/System/File.h>
#include <Spectre/GfxDriver/ShaderProgram.h>
#include <string>

namespace sp 
{

ShaderProgram::~ShaderProgram()
{
}

bool ShaderProgram::loadFromFile(const std::string& filename)
{
    std::string extension = Path::getExtension(filename);

	// Meta file. load real shaders.
	if (extension == "shader." + m_extension) {

		// FIXME: This is ugly :)
		std::string base_name = filename.substr(0, filename.length() - extension.length());

		// vert and frag are not optional. they must exist.
		return	loadFromFile(base_name + "vert." + m_extension, ShaderType::Vertex) &&
			loadFromFile(base_name + "frag." + m_extension, ShaderType::Fragment);

	} else if (extension == "vert." + m_extension) {
		return loadFromFile(filename, ShaderType::Vertex);
	} else if (extension == "frag." + m_extension) {
		return loadFromFile(filename, ShaderType::Fragment);
	}

	m_error = "Invalid file extension: " + extension;

	return false;
}

bool ShaderProgram::loadFromFile(const std::string& filename, ShaderType type)
{
	std::string src;
	File file;

	if (!file.open(filename)) {
		m_error = "Can't open file: " + filename;
		return false;
	}

	// Load file into memory.
	if (!file.read(src)) {
		m_error = "Could not read file: " + filename;
		return false;
	}

	return loadFromMemory(src, type);
}


bool  ShaderProgram::isLinked() const
{
    return m_linked;
}

std::string ShaderProgram::getLastError() const
{
    return m_error;
}

} // namespace sp