package com.utcloud.cookengine;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

/**
 * Created by lixingchen on 2019/12/27.
 */

public class CallBackStub implements CookCallBack {

    Handler mHandler;

    public CallBackStub(Handler handler){
        this.mHandler = handler;
    }

    private void sendMsg(int tag, String msg){
        Message tempMsg = mHandler.obtainMessage();
        tempMsg.what = tag;
        tempMsg.obj = msg.toString();
        mHandler.sendMessage(tempMsg);
    }

    // 函数运行回调
    class MyTask implements Runnable {
        private long _iInstanceId;
        private CookEngine _engine;

        public MyTask(long iInstanceId, CookEngine engine) {
            this._iInstanceId = iInstanceId;
            this._engine = engine;
        }

        @Override
        public void run() {
            System.out.println("正在执行task, intanceid="+ Long.toHexString(_iInstanceId));
            this._engine.destroyInstance(this._iInstanceId);
            System.out.println("task执行完毕");
        }
    }

    private CookEngine engine;
    public void setEngine(CookEngine engine) {
        this.engine = engine;
    }

    public boolean onRunAppFun(long iInstanceId, String taskId, int iCmdId, int iCurStep, int iTotleStep, CookFunItem funItemList[])
    {
        StringBuffer sb = new StringBuffer();
        if (funItemList != null)
        {
            sb.append("onRunAppFun, instanceId=" + Long.toHexString(iInstanceId) + ", funitenlist size=" + funItemList.length + "\n");
            for (int i = 0; i < funItemList.length; ++i)
            {
                sb.append("funitem" + funItemList[i] + "\n");
            }
        }
        // TextView tv = (TextView) findViewById(R.id.sample_text);

        sb.append("onRunAppFun, instanceId=" + Long.toHexString(iInstanceId) + "\n");
        sendMsg(MessageTag.LOG, sb.toString());
        return true;
    }

    // 任务结束回调
    public boolean onEndTask(long iInstanceId, String taskId)
    {
        String msg = "onEndTask, instanceId=" + Long.toHexString(iInstanceId) + ", taskid=" + taskId;
        sendMsg(MessageTag.ON_END_TASK, msg);
        return true;
    }

    // 菜谱结束回调
    public boolean onEndInstance(long iInstanceId, boolean bSuccess)
    {
        String msg ="onEndInstance, instanceId=" + Long.toHexString(iInstanceId);
        sendMsg(MessageTag.ON_END_INSTANCE, msg);

        Thread t = new Thread(new MyTask(iInstanceId, this.engine));
        t.start();

        return true;
    }
}
