/*******************************************************************************
 *	TmsLib.h	TMS Client library functions
 *			T.Barnaby,	BEAM Ltd,	2007-03-14
 *******************************************************************************
 */

#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <math.h>
#include <TmsLib.h>
#include <BDir.h>
#include <BEntry.h>
#include <BFile.h>
#include <TmsCycleParam.h>

namespace Tms {

CycleParamDb::CycleParamDb(BString baseDir){
	obaseDir = baseDir;
}

BError CycleParamDb::getCycleTypes(BList<BString>& typeList){
	BError		err;
	BDir		dir;
	BIter		i;
	BString		n;
	BEntryFile	f;
	
	typeList.clear();
	if(err = dir.open(obaseDir)){
		return err;
	}

	dir.setWild("*_0_0.spt");
	dir.setSort(1);

	for(dir.start(i); !dir.isEnd(i); dir.next(i)){
		if(!f.open(obaseDir + "/" + dir.entryName(i))){
			f.read();
			n = f.findValue("cycleType:");
			
			typeList.append(n);
		}
	}
	
	return err;
}

BError CycleParamDb::getFileNames(BList<BString>& fileList){
	BError		err;
	BDir		dir;
	BIter		i;
	
	fileList.clear();

	if(err = dir.open(obaseDir)){
		return err;
	}

	dir.setWild("*.spt");
	dir.setSort(1);

	for(dir.start(i); !dir.isEnd(i); dir.next(i)){
		fileList.append(dir.entryName(i));
	}
	
	return err;
}


BError CycleParamDb::getCycleParams(BString fileName, Tms::CycleParam& param){
	BString		pathName;
	
	pathName = obaseDir + "/" + fileName;
	
	return readCycleParams(pathName, param);
}

BError CycleParamDb::setCycleParams(Tms::CycleParam param){
	BString		fileName;
	
	fileName = obaseDir + "/" + param.cycleType + "_" + param.ring + "_" + param.channel + ".spt";
	
	return writeCycleParams(fileName, param);
}

BError CycleParamDb::deleteCycleParams(BString cycleType, UInt32 ring, UInt32 puChannel){
	BError		err;
	BDir		dir;
	BIter		i;
	BString		n;
	BEntryFile	f;
	BString		pn;
	
	if(err = dir.open(obaseDir)){
		return err;
	}

	n = "*_";
	
	if(ring)
		n += ring;
	else
		n += "*";

	n += "_";
	
	if(puChannel)
		n += puChannel + ".spt";
	else
		n += "*.spt";
	
	dir.setWild(n);
	
	for(dir.start(i); !dir.isEnd(i); dir.next(i)){
		pn = obaseDir + "/" + dir.entryName(i);
		if(!f.open(pn)){
			f.read();
			n = f.findValue("cycleType:");
			if(n == cycleType){
				unlink(pn);
			}
		}
	}

	return err;
}

BError CycleParamDb::readCycleParams(BString fileName, Tms::CycleParam& param){
	BError		err;
	CycleParamEdit	cp;
	
	if(! (err = cp.readFromFile(fileName))){
		param = cp;
	}
	
	return err;
}

BError CycleParamDb::writeCycleParams(BString fileName, Tms::CycleParam param){
	CycleParamEdit	cp = param;
	
	return cp.writeToFile(fileName);
}

}
