/*
   Copyright (C) 2004 by James Gregory
   Part of the GalaxyHack project
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.
 
   See the COPYING file for more details.
*/

#include "RTSUnit.h"
#include "RTSUnit_Base.h"
#include "Globals.h"
#include "RTSStructs.h"

#include <string>
#include <iterator>
#include <stdexcept>
#include <sstream>
#include <algorithm>

using std::string;
using std::istringstream;
using std::istream_iterator;
using std::runtime_error;
using std::find;
using std::getline;

RTSUnit::RTSUnit(int iMySide, int iMyGroup, UnitType iType, const string& iName) {
	switch (iType) {
	case UT_FrUnit:
		hUnit = new Frigate(iMySide, iMyGroup, iName);
		break;

	case UT_SmShUnit:
		hUnit = new SmallShip(iMySide, iMyGroup, iName);
		break;

	default:
		throw runtime_error("RTSUnit constructor did not recognise group type");
		break;
	}
}

RTSUnit::RTSUnit(int iMySide, int iMyGroup, UnitType iType, const string& iName, CapShipType iCSType) {
	switch (iType) {
	case UT_CaShUnit:
		hUnit = new CapitalShip(iMySide, iMyGroup, iName, iCSType);
		break;

	default:
		throw runtime_error("RTSUnit capital ship constructor did not recognise group type");
		break;
	}
}

string RTSUnit::GetRealPictureName() const {
	string name = hUnit->picName;
	//remove 3 letter extension denoting size of capital ship
	if (GetType() == UT_CaShUnit)
		name.erase(name.size() - 3, 3);

	return name;
}

//only called in ForceSelect
UnitType RTSUnit::WhatUTIsThis(int nSide, string& filename) {
	if (sides[nSide].sdStruct.unitData.find(filename) == sides[nSide].sdStruct.unitData.end()) {
		if (gsCurrent != GST_ForceSelect)
			throw runtime_error("Loading unit data individually and not in ForceSelect");

		string concatName = GetFleetDir(0) + filename + ".dat";
		FileToString(concatName, sides[nSide].sdStruct.unitData[filename]);
	}

	istringstream input(sides[nSide].sdStruct.unitData[filename]);

	string tempStr;

	istream_iterator<char> iter = find(istream_iterator<char>(input), istream_iterator<char>(), ':');
	input.ignore();
	getline(input, tempStr);

	if (tempStr == "Light capital ship"
	        || tempStr == "Medium capital ship"
	        || tempStr == "Heavy capital ship")
		return UT_CaShUnit;

	else if (tempStr == "Frigate")
		return UT_FrUnit;

	else if (tempStr == "Small ship")
		return UT_SmShUnit;

	else throw runtime_error("WhatUTIsThis failed to recognise data file");
}

