package com.utcloud.cookengine;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.utcloud.cookengine.entity.CookTaskInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TASK_ID = "1";

    private TextView mTV;
    private Button but_prepare;
    private Button but_create_inst;
    private Button but_start_task;
    private Button but_skip_curr_step;
    private Button but_pause_task;
    private Button but_resume_task;
    private Button but_terminate_task;

    private Button but_test_auto;
    //private Button but_test_stop;

    private CookEngine cookInstanceEngine = null;
    private Long mInstId = null;

    private byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    private byte[] readLocalFile() throws IOException {
       //String fileName = "bin_sy_mapodoufu.bin";
        String fileName = "v2.2_danrenwu.bin";//""down_taste.bin";
        InputStream inputStream = getAssets().open(fileName);
        byte[] data = toByteArray(inputStream);
        inputStream.close();
        return data;
    }

    private void sleep(long mil){
        try {
            Thread.sleep(mil);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void button_setvisiable(boolean isAuto){
        if(isAuto){
            but_create_inst.setVisibility(View.INVISIBLE);
            but_start_task.setVisibility(View.INVISIBLE);
            but_skip_curr_step.setVisibility(View.INVISIBLE);
            but_pause_task.setVisibility(View.INVISIBLE);
            but_resume_task.setVisibility(View.INVISIBLE);
            but_terminate_task.setVisibility(View.INVISIBLE);
        }else{
            but_test_auto.setVisibility(View.INVISIBLE);
            //but_test_stop.setVisibility(View.INVISIBLE);
        }
    }

    private void button_init(){
        but_create_inst.setEnabled(true);
        but_start_task.setEnabled(false);
        but_skip_curr_step.setEnabled(false);
        but_pause_task.setEnabled(false);
        but_resume_task.setEnabled(false);
        but_terminate_task.setEnabled(false);

        but_test_auto.setEnabled(true);
        //but_test_stop.setEnabled(false);
    }

    private void button_terminate_task(){
        but_create_inst.setEnabled(false);
        but_start_task.setEnabled(true);
        but_skip_curr_step.setEnabled(false);
        but_pause_task.setEnabled(false);
        but_resume_task.setEnabled(false);
        but_terminate_task.setEnabled(false);
    }

    private void showToast(String msg){
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 预加载菜谱
     * @return
     */
    boolean prepareCook(){
        byte[] binData = new byte[0];
        try {
            binData = readLocalFile();
        } catch (IOException e) {
            showToast(e.getMessage());
            return false;
        }

        if(null == cookInstanceEngine){
            CallBackStub callBackStub = new CallBackStub(mHandler);
            cookInstanceEngine = new CookEngine(callBackStub);
            callBackStub.setEngine(cookInstanceEngine);
        }

        // 获取xml数据
        byte[] xmlData = cookInstanceEngine.prepareGetExternData(binData);
        System.out.println("xmlData len=" + xmlData.length + ", content=" + new String(xmlData));


        // 获取任务信息
        byte taskInfoBytes[]= cookInstanceEngine.prepareGetTaskInfo(binData);
        ArrayList<CookTaskInfo> taskList = null;
        if(null != taskInfoBytes){
            String taskInfoJson = new String(taskInfoBytes);
            System.out.println( "taskInfoList=" + taskInfoJson);
            mTV.setText(taskInfoJson);
            try {
                taskList = JSONObject.parseObject(taskInfoJson, new TypeReference<ArrayList<CookTaskInfo>>() {
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        return true;
    }


    /**
     * 创建菜谱实例
     * @return
     */
    boolean createCookInstance(){
        byte[] binData = new byte[0];
        try {
            binData = readLocalFile();
        } catch (IOException e) {
            showToast(e.getMessage());
            return false;
        }

        if(null == cookInstanceEngine){
            CallBackStub callBackStub = new CallBackStub(mHandler);
            cookInstanceEngine = new CookEngine(callBackStub);
            callBackStub.setEngine(cookInstanceEngine);
        }

        // 创建菜谱实例，动态参数为：分量为1份，档位为1
        //String cfgParams = "quantity=1;taste=0;level=2";
        String cfgParams = "quantity=1";
        long instId =  cookInstanceEngine.createInstance(binData, cfgParams);
        mInstId = instId;
        System.out.println("instanceid=" + Long.toHexString (instId) );

        // 获取xml数据
        byte[] xmlData = cookInstanceEngine.getExternData(instId);
        System.out.println("xmlData len=" + xmlData.length + ", content=" + new String(xmlData));

        // 获取任务信息
        byte taskInfoBytes[]= cookInstanceEngine.getTaskInfo(instId);
        ArrayList<CookTaskInfo> taskList = null;
        if(null != taskInfoBytes){
            String taskInfoJson = new String(taskInfoBytes);
            System.out.println( "taskInfoList=" + taskInfoJson);

            try {
                taskList = JSONObject.parseObject(taskInfoJson, new TypeReference<ArrayList<CookTaskInfo>>() {
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        but_create_inst.setEnabled(false);
        but_start_task.setEnabled(true);

        return true;
    }


    void startTask(){
        // 关联虚拟机的设备id
        HashMap<Long, String> trueProductMap = new HashMap<>();
        trueProductMap.put(new Long(4), "host");
        trueProductMap.put(new Long(3), "batcher_business_multi_export");
        trueProductMap.put(new Long(0), "bizcooker_stirfry_18kw");

        // 开始任务
        boolean startTaskRet = cookInstanceEngine.startTask(mInstId, TASK_ID, trueProductMap);
        System.out.println("start task=" + startTaskRet);
        if(startTaskRet){
            but_start_task.setEnabled(false);
            but_skip_curr_step.setEnabled(true);
            but_pause_task.setEnabled(true);
            but_terminate_task.setEnabled(true);
        }
    }

    void skipCurrentStep(){
        cookInstanceEngine.skipCurrentStep(mInstId, TASK_ID);
    }

    void pauseTask(){
        // 暂停任务
        boolean pauseTaskRet = cookInstanceEngine.pauseTask(mInstId, TASK_ID);
        System.out.println("pause task=" + pauseTaskRet);
        if(pauseTaskRet){
            but_skip_curr_step.setEnabled(false);
            but_pause_task.setEnabled(false);
            but_resume_task.setEnabled(true);
        }
    }

    void resumeTask() {
        // 恢复任务
        boolean resumeTaskRet = cookInstanceEngine.resumeTask(mInstId, TASK_ID);
        System.out.println("resume task=" + resumeTaskRet);
        if(resumeTaskRet){
            but_skip_curr_step.setEnabled(true);
            but_pause_task.setEnabled(true);
            but_resume_task.setEnabled(false);
        }
    }

    void terminateTask() {
        // 恢复任务
        boolean resumeTaskRet = cookInstanceEngine.terminateTask(mInstId, TASK_ID);
        System.out.println("terminate task=" + resumeTaskRet);
        if(resumeTaskRet){
            button_terminate_task();
        }
    }

    void postEvent() {
        // 发送事件
        //engine.postEvent(instId, 0, "Enter", "1");
    }

    //更新log信息
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case MessageTag.LOG:
                    mTV.setText((String) msg.obj);
                    break;
                case MessageTag.ON_END_TASK:
                    button_terminate_task();
                    mTV.setText((String) msg.obj);
                    break;
                case MessageTag.ON_END_INSTANCE:
                    button_init();
                    mTV.setText((String) msg.obj);
                    break;
            }
        };
    };

    private boolean auto_test_terminal = false;
    protected void auto_test_start(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(!auto_test_terminal){

                        byte[] binData = new byte[0];
                        try {
                            binData = readLocalFile();
                        } catch (IOException e) {
                            showToast(e.getMessage());
                        }

                        CallBackStub callBackStub = new CallBackStub(mHandler);
                        CookEngine engine = new CookEngine(callBackStub);
                        callBackStub.setEngine(engine);

                        // 创建菜谱实例，动态参数为：分量为1份，档位为1
                        //String cfgParams = "quantity=1;taste=0;level=2";
                        String cfgParams = "quantity=1";
                        long instId = engine.createInstance(binData, cfgParams);
                        System.out.println("instanceid=" + Long.toHexString(instId));
                        // 获取xml数据
                        byte[] xmlData = engine.getExternData(instId);
                        xmlData = engine.getExternData(instId);
                        xmlData = engine.getExternData(instId);
                        System.out.println("xmlData len=" + xmlData.length + ", content=" + new String(xmlData));

                        // 关联虚拟机的设备id
                        HashMap<Long, String> trueProductMap = new HashMap<>();
                        trueProductMap.put(new Long(4), "host");
                        trueProductMap.put(new Long(3), "batcher_business_multi_export");
                        trueProductMap.put(new Long(0), "bizcooker_stirfry_18kw");

                        // 开始任务
                        boolean startTaskRet = engine.startTask(instId, TASK_ID, trueProductMap);
                        System.out.println("start task=" + startTaskRet);


                        sleep(45000);
                    }
                }
            }).start();
    }


    private View.OnClickListener but_clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch(view.getId()){
                case R.id.but_prepare:
                    prepareCook();
                    break;
                case R.id.but_create_inst:
                    button_setvisiable(false);
                    createCookInstance();
                    break;
                case R.id.but_start_task:
                    startTask();
                    break;
                case R.id.but_skip_curr_step:
                    skipCurrentStep();
                    break;
                case R.id.but_pause_task:
                    pauseTask();
                    break;
                case R.id.but_resume_task:
                    resumeTask();
                    break;
                case R.id.but_terminate_task:
                    terminateTask();
                    break;
                case R.id.but_test_auto:
                    button_setvisiable(true);
                    but_test_auto.setEnabled(false);
                    //but_test_stop.setEnabled(true);
                    auto_test_start();
                    break;
//                case R.id.but_test_stop:
//                    but_test_auto.setEnabled(true);
//                    but_test_stop.setEnabled(false);
//                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTV= (TextView) findViewById(R.id.sample_text);
        mTV.setText("hello");

        but_prepare = (Button) findViewById(R.id.but_prepare);
        but_create_inst = (Button) findViewById(R.id.but_create_inst);
        but_start_task = (Button) findViewById(R.id.but_start_task);
        but_skip_curr_step = (Button) findViewById(R.id.but_skip_curr_step);
        but_pause_task = (Button) findViewById(R.id.but_pause_task);
        but_resume_task = (Button) findViewById(R.id.but_resume_task);
        but_terminate_task = (Button) findViewById(R.id.but_terminate_task);

        but_test_auto = (Button) findViewById(R.id.but_test_auto);

        button_init();

        but_prepare.setOnClickListener(but_clickListener);
        but_create_inst.setOnClickListener(but_clickListener);
        but_start_task.setOnClickListener(but_clickListener);
        but_skip_curr_step.setOnClickListener(but_clickListener);
        but_pause_task.setOnClickListener(but_clickListener);
        but_resume_task.setOnClickListener(but_clickListener);
        but_terminate_task.setOnClickListener(but_clickListener);
        but_test_auto.setOnClickListener(but_clickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    // public native String stringFromJNI(Object obj, HashMap<Long, String> mapData);
}
