package org.bench4q.master.unitTest.service;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.domain.service.PluginService;
import org.bench4q.master.unitTest.testHelper.Test_PluginHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:mockHttpMesseger-context.xml" })
public class Test_PluginService extends Test_PluginHelper {
	private PluginService pluginService;
	private String pluginName;
	private String pluginFileName = "hbase.xml";
	private PluginRepository pluginRepository;

	public PluginService getPluginService() {
		return pluginService;
	}

	@Autowired
	public void setPluginService(PluginService pluginService) {
		this.pluginService = pluginService;
	}

	public PluginRepository getPluginRepository() {
		return pluginRepository;
	}

	@Autowired
	public void setPluginRepository(PluginRepository pluginRepository) {
		this.pluginRepository = pluginRepository;
	}

	@Before
	public void setUp() {
		this.pluginName = "hbase";
		this.getPluginRepository().detach(pluginName);
	}

	@After
	public void clear() {

	}

	@Test
	public void test_addPlugin() {
		this.getPluginService().deletePlugin(pluginName);
		File file = new File(filePath(pluginFileName));
		String pluginContent;
		try {
			pluginContent = FileUtils.readFileToString(file);
			assertNotNull(pluginContent);
			assertTrue(this.getPluginService().addPlugin(pluginContent));
			assertFalse(this.getPluginService().addPlugin(pluginContent));
			assertTure(this.getPluginService().deletePlugin(pluginName));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Test
	public void test_loadPlugins() {
		int insertBefore = this.getPluginService().loadPluginUIs().size();
		addPluginByString();
		assertEquals(insertBefore + 1, this.getPluginService().loadPluginUIs()
				.size());
		this.getPluginService().deletePlugin(pluginName);
	}

	@Test
	public void test_loadBehaviors() {
		addPluginByString();
		assertEquals(1,
				this.getPluginService().loadBehaviorInfoModels(pluginName)
						.size());
	}

	private void assertTure(boolean deletePlugin) {

	}

	private void addPluginByString() {
		File file = new File(filePath(pluginFileName));
		String pluginContent;
		try {
			pluginContent = FileUtils.readFileToString(file);
			this.getPluginService().addPlugin(pluginContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
