/* ////////// LICENSE INFO ////////////////////

 * Copyright (C) 2013 by NYSOL CORPORATION
 *
 * Unless you have received this program directly from NYSOL pursuant
 * to the terms of a commercial license agreement with NYSOL, then
 * this program is licensed to you under the terms of the GNU Affero General
 * Public License (AGPL) as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF 
 * NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Please refer to the AGPL (http://www.gnu.org/licenses/agpl-3.0.txt)
 * for more details.

 ////////// LICENSE INFO ////////////////////*/
// =============================================================================
// kgvsort.cpp ベクトル要素の並べ替えクラス
// =============================================================================
#include <cstdio>
#include <sstream>
#include <vector>
#include <kgvsort.h>
#include <kgError.h>
#include <kgMethod.h>
#include <kgConfig.h>

using namespace std;
using namespace kglib;
using namespace kgmod;


namespace kgvsort_local {//////////////////////////////////////////////////

	// 文字列昇順
	inline int cmpStrAsc(unsigned char* a, unsigned char* b)
	{
		while(true){
		       if(*a < *b) return  1;
			else if(*a > *b) return -1;
			if(*a=='\0') break; // *a==*b=='\0'
			a++;b++;
		}
		return 0;
	}
	// 文字列降順
	inline int cmpStrDec(unsigned char* a, unsigned char* b)
	{
		while(true){
		       if(*a < *b) return -1;
			else if(*a > *b) return  1;
			if(*a=='\0') break; // *a==*b=='\0'
			a++;b++;
		}
		return 0;
	}
	// 数値昇順
	inline int cmpNumAsc(char* a, char* b)
	{
		if(*a=='\0'){
			if(*b=='\0') return 0;
			else         return 1;
		}else{
			if(*b=='\0') return -1;
			double fa=atof(a);
			double fb=atof(b);
		       if(fa < fb) return  1;
			else if(fa > fb) return -1;
			else             return  0;
		}
		return 0;
	}
	// 数値降順
	inline int cmpNumDec(char* a, char* b)
	{
		if(*a=='\0'){
			if(*b=='\0') return 0;
			else         return -1;
		}else{
			if(*b=='\0') return 1;
			double fa=atof(a);
			double fb=atof(b);
		       if(fa < fb) return -1;
			else if(fa > fb) return  1;
			else             return  0;
		}
		return 0;
	}
	// 比較クラス
	struct itmComp 
	{
		int type;//0:文字ソート,1:数字ソート,2:文字逆ソート,3:数字逆ソート
		itmComp(void){type=0;}
		itmComp(int x){type = x;}

 		bool operator()(char* v1, char* v2) {
 			int retVal=0;
			switch( type ){
				case 0: // 文字昇順
				retVal=cmpStrAsc((unsigned char*)v1, (unsigned char*)v2);
				break;
			case 1: // 数字昇順
				retVal=cmpNumAsc(v1, v2);
				break;
			case 2: // 文字降順
				retVal=cmpStrDec((unsigned char*)v1, (unsigned char*)v2);
				break;
			case 3: // 数字降順
				retVal=cmpNumDec(v1, v2);
				break;
	 		}
	   	if( retVal>0 ){ return true;}
  	 	else       		{ return false;}
  	 	return false;
  	}

};

} //////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// コンストラクタ(モジュール名，バージョン登録)
// -----------------------------------------------------------------------------
kgVsort::kgVsort(void)
{
	#ifdef ENG_FORMAT
		#include <help/en/kgvsortHelp.h>
	#else
		#include <help/jp/kgvsortHelp.h>
	#endif
	_name    = "kgvsort";
	_version = "1.0";
}

// -----------------------------------------------------------------------------
// 入出力ファイルオープン
// -----------------------------------------------------------------------------
void kgVsort::setArgs(void)
{
	// パラメータチェック
	_args.paramcheck("i=,o=,vf=,delim=");

	// 入出力ファイルオープン
	_iFile.open(_args.toString("i=",false),_env,_nfn_i);
	_oFile.open(_args.toString("o=",false),_env,_nfn_o);
	_iFile.read_header();

	// vf= 項目引数のセット
	vector< vector<kgstr_t> > vvs = _args.toStringVecVec("vf=","%:",2,true);
	_vfField.set(vvs, &_iFile,_fldByNum, false); // 項目名展開は行わない

	// delim= 項目引数のセット
	kgstr_t s_d = _args.toString("delim=",false);
	if(s_d.empty()){	
		_delim=' ';
	}else if(s_d.size()!=1){
		ostringstream ss;
		ss << "delim= takes 1 byte charactor (" << s_d << ")";
		throw kgError(ss.str());
	}else{
		_delim=*(s_d.c_str());
	}

}
// -----------------------------------------------------------------------------
// 実行
// -----------------------------------------------------------------------------
void kgVsort::run(void) try 
{
	// パラメータセット＆入出力ファイルオープン
	setArgs();

	// 項目名出力
  _oFile.writeFldName(_iFile);

	vector <kgvsort_local::itmComp> icomp;
	for(size_t i=0; i<_vfField.size(); i++){
		kgstr_t s=_vfField.attr(i);
		int flg=0;
		if( s.find('n')!=kgstr_t::npos ) flg |= 1;
		if( s.find('r')!=kgstr_t::npos ) flg |= 2;
		icomp.push_back(kgvsort_local::itmComp(flg));
	}
	
	//文字列生成用領域
	char delimstr[2];
	delimstr[0] =_delim;
	delimstr[1] ='\0';
	char buf[KG_MAX_STR_LEN];

	while(EOF != _iFile.read() ){
		for(size_t i=0; i<_iFile.fldSize(); i++){
			char* str=_iFile.getVal(i);
			if(_vfField.flg(i)!=-1){

				// itemset項目を" "でトークン分割してソート
				vector<char*> eachItem = splitToken( str ,_delim);
				sort(eachItem.begin(),eachItem.end(),icomp[_vfField.flg(i)]);
				
				//出力文字列生成
				*buf = '\0'; 
				int len = 0; 
				for(vector<char*>::iterator j=eachItem.begin(); j!=eachItem.end(); j++){
					len += (strlen(delimstr)+strlen(*j));
					if(len>=KG_MAX_STR_LEN){ throw kgError("field length exceeded KG_MAX_STR_LEN");}
					if(*buf!='\0'){ strcat(buf,delimstr); }
					strcat(buf,*j);
				}

				if(i+1==_iFile.fldSize()) _oFile.writeStr(buf,true );
				else                      _oFile.writeStr(buf,false);
			}
			else{
				if(i+1==_iFile.fldSize()) _oFile.writeStr(str,true );
				else                      _oFile.writeStr(str,false);
			}
		}
	}

	// 終了処理(メッセージ出力,thread pipe終了通知)
	_iFile.close();
	_oFile.close();
	successEnd();

}catch(kgError& err){

	errorEnd(err);

}
