package com.cftech.core.mybatis;


import java.io.*;

/**
 * Created by lisw on 2016-08-05
 */
public abstract class AbstractGenerator {

	/**
	 * 点
	 */
	protected final String pointStr = ".";

	/**
	 * semicolon
	 */
	protected final String semicolon = ";";

	/**
	 * enter
	 */
	protected final String enter = "\n";

	/**
	 * tab
	 */
	protected final String tab = "\t";

	/**
	 * 空格键
	 */
	protected final String blank = " ";

	/**
	 * isBlank
	 * @param cs
	 * @return boolean
	 */
	protected boolean isBlank(final CharSequence cs) {
		int strLen;
		if (cs == null) {
			return true;
		}
		strLen = cs.length();
		if (strLen == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(cs.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * isNotBlank
	 * @param cs
	 * @return boolean
	 */
	protected boolean isNotBlank(final CharSequence cs) {
		return !isBlank(cs);
	}

	/**
	 * isFileExists
	 * @param filePath
	 * @return boolean
	 */
	protected boolean isFileExists(final String filePath) {
		return isFileExists(new File(filePath));
	}

	/**
	 * isFileExists
	 * @param file
	 * @return boolean
	 */
	protected boolean isFileExists(final File file) {
		if (file != null) {
			return file.exists();
		}
		return false;
	}

	/**
	 * generateJavaFile
	 * @param filePath
	 * @param source
	 * @return boolean
	 */
	protected boolean outputJavaFile(String filePath, String source) {
		File file = new File(filePath);
		if (isFileExists(file)) {
			return false;
		}
		File parentDirectory = file.getParentFile();
		if (!parentDirectory.exists()) {
			parentDirectory.mkdirs();
		}
		this.str2File(file, source);
		return true;
	}

	/**
	 * str 2 file
	 * @param file
	 * @param source
	 */
	private void str2File(File file, String source) {
		ByteArrayInputStream stream = new ByteArrayInputStream(source.getBytes());
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			int bytesRead = 0;
			final int buffSize = 8192;
			byte[] buffer = new byte[buffSize];
			while ((bytesRead = stream.read(buffer, 0, buffSize)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (stream != null) {
					stream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
