package jp.agentec.abook.abv.cl.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.adf.util.FileUtil;
import jp.agentec.adf.util.StringUtil;
import android.content.Context;

public class RawResourceUtil {
	private static final String TAG = "RawResourceUtil";

	public static String getGitHash(Context ctx) {
		String gitHash = "";
		try {
			gitHash = FileUtil.readTextFile(ctx.getAssets().open("githash.txt"));
			gitHash = StringUtil.chomp(gitHash);
		} catch (Exception e) {
			Logger.e(TAG, "read gitHash failed.", e);
		}
		return gitHash;
	}
	
	public static String getShortGitHash(Context ctx) {
		String gitHash = getGitHash(ctx);
		if (gitHash != null && gitHash.length() > 8) {
			return gitHash.substring(0, 8);
		}
		return gitHash;
	}
	
	public static String readAsString(Context ctx, int resId) {
		InputStream is = null;
		try {
			is = ctx.getResources().openRawResource(resId);
			StringBuilder sb = new StringBuilder();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String str;
			while ((str = br.readLine()) != null) {
				sb.append(str + "\n");
			}
			return sb.toString();
		}
		catch (IOException e) {
			Logger.e(TAG, "read res failed." + resId, e);
			return null;
		}
		finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					Logger.e(TAG, "read close failed." + resId, e);
				}
			}
		}
	}

}
