package org.bench4q.master.domain.service;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.entity.TestPlanScriptResult;
import org.bench4q.master.domain.repository.TestPlanRepository;
import org.bench4q.master.helper.SessionHelper;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestPlanScriptService  {
//	private static Logger logger = Logger.getLogger(TestPlanService.class);
	private SessionHelper sessionHelper;
	private TestPlanRepository testPlanRepository;


	private SessionHelper getSessionHelper() {
		return sessionHelper;
	}

	@Autowired
	private void setSessionHelper(SessionHelper sessionHelper) {
		this.sessionHelper = sessionHelper;
	}

	private TestPlanRepository getTestPlanRepository() {
		return testPlanRepository;
	}

	@Autowired
	private void setTestPlanRepository(TestPlanRepository testPlanRepository) {
		this.testPlanRepository = testPlanRepository;
	}

	
	public TestPlanScript getTestPlanScript(int scriptId, UUID testPlanRunId) {
		TestPlan testPlan = this.getTestPlanRepository().getTestPlanInDomainBy(
				testPlanRunId);
		return testPlan == null ? null : testPlan
				.extracSpecifiedScript(scriptId);
	}


	public Collection<TestPlanScript> queryTestPlanScripts(UUID testPlanRunId) {
		return this.getTestPlanRepository().getTestPlanInDomainBy(testPlanRunId)
				.getTestPlanScripts();
	}

	public List<TestPlanScriptResult> queryScriptBriefResults(UUID testPlanId,
			int scriptId) {
		return queryScriptBriefResults(this.getTestPlanScript(scriptId,
				testPlanId));
	}

	public List<TestPlanScriptResult> queryScriptBriefResults(
			TestPlanScript testPlanScript) {
		return queryScriptResultsByType(testPlanScript,
				ScriptBriefResultModel.class.getName());
	}

	private List<TestPlanScriptResult> queryScriptResultsByType(
			TestPlanScript testPlanScript, String type) {
		Session session = this.getSessionHelper().openSession();
		try {
			@SuppressWarnings("unchecked")
			List<TestPlanScriptResult> resultList = session
					.createCriteria(TestPlanScriptResult.class)
					.add(Restrictions.eq("testPlanScript", testPlanScript))
					.add(Restrictions.eq("resultType", type)).list();
			return resultList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

}
