package mobvista.dmp.common;

import mobvista.dmp.util.MRUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * author: houying
 * date  : 16-11-10
 * desc  :
 */
public class InterestPackageJoinMR extends CommonMapReduce {

    public InterestPackageJoinMR(String name, Class<? extends Mapper> mapperClass, Class<? extends Reducer> reducerClass) {
        super(name, mapperClass, reducerClass);
    }

    public static class InterestPackageJoinMapper extends CommonMapper {
        private ObjectMapper objectMapper;
        private JavaType javaType;
        private Map<String, String> broadcast;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            objectMapper = new ObjectMapper();
            javaType = objectMapper.getTypeFactory().constructMapType(HashMap.class, String.class, String.class);

            try {
                // 将broadcast反序列化成map对象
                String convert = context.getConfiguration().get(Constants.MR_BROADCAST_STR);
                broadcast = decodeObject(convert, HashMap.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] array = MRUtils.SPLITTER.split(value.toString(), -1);
            if (array.length != 4) {
                CommonMapReduce.setMetrics(context,"DMP","column_num_error",1);
                return;
            }

            String deviceId = array[0];
            String deviceType = array[1];
            String platform = array[2];
            JsonNode appList = objectMapper.readTree(array[3]);
            for (JsonNode app: appList) {
                Map<String, String> map = objectMapper.readValue(app, javaType);
                String packageName = map.get("package_name");
                String tags = broadcast.get(packageName);
                if (tags != null) {
                    outKey.set(MRUtils.JOINER.join(
                            deviceId,
                            deviceType,
                            platform
                    ));

                    outValue.set(MRUtils.JOINER.join(
                            packageName,
                            tags
                    ));
                    context.write(outKey, outValue);
                }
            }
        }
    }

    @Override
    protected void otherSetting(Job job, String[] args) throws Exception {
        job.setNumReduceTasks(0);

        // 读取广播内容，用于map side join
        Configuration conf = job.getConfiguration();
        Map<String, String> broadcast = buildBroadcast(args[0], conf, 0, 3);
        String convert = encodeObject(broadcast);
        conf.set(Constants.MR_BROADCAST_STR, convert);
    }

    @Override
    protected void setOutputPath(Job job, String[] args) throws IOException {
        FileOutputFormat.setOutputPath(job, new Path(args[2]));
        FileOutputFormat.setCompressOutput(job, false);
    }

    @Override
    protected void setInputPath(Job job, String[] args) throws IOException {
        FileInputFormat.addInputPath(job, new Path(args[1]));
    }

    public static void main(String[] args) throws Exception {
        start(new InterestPackageJoinMR("interest package join job", InterestPackageJoinMapper.class, null), args);
    }
}
