#include "ats_MBoidGlobal.h"

#include "ats_MayaBoid.h"
#include <maya/MItSelectionList.h>
#include <maya/MSelectionList.h>
using namespace ats;
using namespace std;

bool operator==(const ats::StructArg* a, const MString& b){
	return *a == b;
}

std::ostream& operator<<(std::ostream& out, const MString& a)
{
	cout << a.asChar();
	return out;
}

std::ostream& operator<<(std::ostream& out, const MStringArray& a)
{
	for(int i=0; i < a.length(); i++){
		cout << a[i] << ' ';
	}
	return out;
}

std::ostream& operator<<(std::ostream& out, const ats::StructArg& a)
{
	out << a.str.asChar() << ' ' << a.num << '\n';
	for(int i=0; i < a.num; i++){
		out << a.val[i] << ' ';
	}
	out << endl;
	return out;
}

void ats::ParseArg(const MArgList& args, vector<StructArg*>* arg_pack) throw (MException)
{
	MStatus status;
	for (int i = 0; i < args.length(); i++ ){
		// 文字ゲット
		MString str = args.asString(i, &status);
			if(MS::kSuccess != status){ throw MException("1. 引数指定が不正です。", status); }
		// 一致サーチ
		vector<StructArg*>::iterator arg_type;
		arg_type = find(arg_pack->begin(), arg_pack->end(), str);
		// 一致の有無で分岐
		if(arg_pack->end() == arg_type){
			throw MException("2. 引数指定が不正です。", MS::kFailure);
		} else {
			// パッケージを開封。内容に従って入力処理。
			for(int j=0; j < (*arg_type)->num; j++){
				double tmp = args.asDouble(++i, &status);
				if(MS::kSuccess != status){
					throw MException("3. 引数指定が不正です。", status);
				}
				(*arg_type)->val[j] = tmp;
			}
		}
	}
}

void ats::GetFirstSelection(MDagPath* path, MObject* obj) throw (MException)
{
	MStatus status;
	MSelectionList sList;
	MGlobal::getActiveSelectionList( sList ); 	// 現在の選択オブジェクトを取得
	MItSelectionList itr(sList, MFn::kDagNode, &status);
	if ( MS::kSuccess != status ) {
		throw MException("Failure Creating Selection List in GetFirstSelectiont\n", status);
	}
	// 選択されたオブジェクトのDAGパスを取得
	itr.getDagPath(*path, *obj);
}

void ats::MakeMayaBoid(BoidGroup* group, int copy_number, const StructArg& weight, const StructArg& ball, const StructArg& speed) throw (MException)
{
	MDagPath original_path;
	MObject original; // カーブ出力先のオリジナル
	GetFirstSelection(&original_path, &original); // 最初の選択オブジェクトをオリジナルとする。

	for(int i=0; i < copy_number; i++){
		// 0.05, 0.08, 1.1;
		group->Add(new MayaBoid(original_path, 2, speed.val[0], ball.val[3], weight.val[0], weight.val[1], weight.val[2]));
	}
}


