package cc.winboll.studio.regexputils.develop;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.winboll.studio.regexputils.develop.LogUtils;
import java.lang.ref.WeakReference;

public class LogView extends LinearLayout {

    public static final String TAG = "LogView";
    
    final static int MSG_SHOW_LOG = 0;

    LogListener mLogListener;
    ScrollView mScrollView;
    TextView mTextView;
    MyHandler mMyHandler;

    public LogView(Context context) {
        super(context);
        initView(context);
    }

    public LogView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    void initView(Context context) {
        mScrollView = new ScrollView(context);
        mTextView = new TextView(context);
        mTextView.setTextColor(Color.GREEN);
        mTextView.setTextIsSelectable(true);

        mScrollView.addView(mTextView);
        addView(mScrollView);
        
        mMyHandler = new MyHandler(this);

        mLogListener = new LogListener(WinBollBase._mszLogFolderPath);
        mLogListener.setEventCallback(new LogListener.EventCallback(){
                @Override
                public void onEvent(String path) {
                    Message message = mMyHandler.obtainMessage(MSG_SHOW_LOG);
                    mMyHandler.sendMessage(message);
                    
                }
            });
    }

    public void startWatching() {
        mLogListener.startWatching();
    }

    public void stopWatching() {
        mLogListener.stopWatching();
    }
    
    static class MyHandler extends Handler {
        WeakReference<LogView> rv;  
        MyHandler(LogView view) {  
            rv = new WeakReference<LogView>(view);  
        }
        public void handleMessage(Message msg) {
            final LogView view = rv.get();
            switch (msg.what) {
                case MSG_SHOW_LOG:{
                        view.mTextView.setText(LogUtils.loadLog());
                        view.mScrollView.post(new Runnable() {
                                @Override
                                public void run() {
                                    view.mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                                }
                            });
                        break;
                }
                    
                    
                default:
                    break;
            }
            super.handleMessage(msg);
        }
	}
}
