package com.xxx.yyy;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.appengine.jae.api.task.AbstractPrefetchTask;
import com.alibaba.appengine.jae.api.task.PrefetchSet;
import com.alibaba.appengine.jae.api.task.PrefetchSet.Row;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class MyPrefetchTask extends AbstractPrefetchTask {

    private static final Logger        logger = LoggerFactory.getLogger(MyPrefetchTask.class);

    private static final AtomicInteger count  = new AtomicInteger(0);

    @Override
    public void run(String[] args, Row row) {
        logger.info("args: " + StringUtils.join(args, " , "));
        logger.info(printRow(row));

        logger.info(ToStringBuilder.reflectionToString(row));
        new Thread(new Runnable() {

            public void run() {
                System.out.println("print by sysout in new thread.");
                logger.warn("log by logger in new thread.count: " + count.addAndGet(1));

            }
        }).start();
        System.out.println("---------------hello---------------" + row.get("id"));
    }

    @Override
    public String afterRun(String[] args, PrefetchSet ps) {
        count.set(0);
        logger.warn("log by logger in afterRun.count: " + count.addAndGet(1));
        JSONObject obj = JSON.parseObject(args[0]);
        Boolean error = (obj != null) ? obj.getBoolean("error") : null;
        if (error != null && error.booleanValue()) {
            throw new RuntimeException("failed to run task");
        }
        Long sleep = (obj != null) ? obj.getLong("sleep") : null;
        if (sleep != null) {
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String output = (obj != null) ? obj.getString("output") : null;
        if (StringUtils.isNotBlank(output)) {
            return output;
        }
        return "OK";
    }

    private String printRow(Row row) {
        if (row == null || row.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (String key : row.keySet()) {
            sb.append(key).append("=").append(row.get(key)).append(";");
        }
        return sb.toString();
    }
}
