package jp.sourceforge.nicoro;

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

//import jp.gr.java_conf.shiseissi.commonlib.APILevelWrapper;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
//import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.webkit.WebView;

import static jp.sourceforge.nicoro.Log.LOG_TAG;;

public class NicoroHelp extends Activity {

	WebView mWebView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mWebView = new WebView(this);	// use Activity context
		setContentView(mWebView);
		loadHelp(this, mWebView);
	}

    @Override
    protected void onStart() {
        super.onStart();

        // TODO 戻り先はDashBoardとログイン画面両方の可能性がある
//        APILevelWrapper api = APILevelWrapper.createInstance();
//        api.setDisplayHomeAsUpEnabled_ActionBar(this, true);
    }

	@Override
	protected void onResume() {
	    super.onResume();
	    mWebView.resumeTimers();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // TODO 戻り先はDashBoardとログイン画面両方の可能性がある
//                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

	public static void loadHelp(Context context, WebView webView) {
        InputStream in = null;
        InputStreamReader reader = null;
        try {
            in = context.getAssets().open("help.html");
            reader = new InputStreamReader(in, "utf-8");
            char[] buffer = new char[8192];
            StringBuilder builder = new StringBuilder(8192);
            while (true) {
                int readSize = reader.read(buffer);
                if (readSize < 0) {
                    break;
                }
                builder.append(buffer, 0, readSize);
            }
            webView.loadDataWithBaseURL(
                    "file:///android_asset/",
                    builder.toString(),
                    "text/html",
                    "utf-8",
                    null);
        } catch (IOException e) {
            Log.w(LOG_TAG, e.toString(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.d(LOG_TAG, e.toString(), e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.d(LOG_TAG, e.toString(), e);
                }
            }
        }
	}
}
