#include "SingleECUFlasher.hpp"
#include "TimeUtils.h"
#include <thread>

namespace otx {
	namespace flash {

		SingleECUFlasher::SingleECUFlasher() :ECUFlasherImpl() {
			this->mECU = nullptr;
		}

		ECU* SingleECUFlasher::getECU() {
			return this->mECU;
		}
		void SingleECUFlasher::setECU(ECU* ecu) {
			this->mECU = ecu;
			std::vector<otx::flash::File>* files = this->mECU->getFiles();
			int size = files->size();
			for (int i = 0; i < size; i++) {
				File ecuFile = files->at(i);
				this->mTotalSize += ecuFile.getSize();
			}
		}

		bool SingleECUFlasher::download() {
			//执行ecu的刷写，按顺序刷写其中的文件。
			// 该方法是同步方法，所有文件刷写完成后返回。
			otx::flash::ECUFlasherECUEventArg arg(this, this->mECU);
			postECUDownloadStart(arg);

			this->mStartTime = getTimeStamp();
			std::vector<otx::flash::File>* files = this->mECU->getFiles();
			int size = files->size();

			bool isSucceed = true;
			for (int i = 0; i < size; i++) {
				File ecuFile = files->at(i);
				isSucceed = downloadFile(this->mECU, &ecuFile);
				if (!isSucceed) {
					break;
				}
			}

			this->mDownloadedSize = this->mTotalSize;
			otx::flash::ECUFlasherECUEventArg endArg(this, this->mECU, isSucceed);
			postECUDownloadEnd(endArg);

			return isSucceed;
		}

	} // namespace flash
} // namespace otx