package mobvista.dmp.datasource.adn.mapreduce;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import mobvista.dmp.common.CommonMapReduce;
import mobvista.dmp.common.CommonMapper;
import mobvista.dmp.common.Constants;
import mobvista.dmp.util.MRUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.GzipCodec;
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.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: houying
 * date  : 16-10-19
 * desc  :
 */
public class AdnSdkInterestTotalMRv2 extends CommonMapReduce {
    private static final Logger logger = LoggerFactory.getLogger(AdnSdkInterestTotalMRv2.class);

    public static void main(String[] args) throws Exception {
        start(new AdnSdkInterestTotalMRv2(args[4], AdnSdkMapper.class, null), args);
    }

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

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

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

            try {
                // 将broadcast反序列化成map对象
                Configuration conf = context.getConfiguration();
                String tag = conf.get(Constants.MR_BROADCAST_STR);
                tagMap = buildBroadcast(tag, conf, 0, 3);
            } 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) { //dm_install_tag
                return;
            }
            JsonNode appList = objectMapper.readTree(array[3]);
            List<Map<String, Object>> list = Lists.newArrayListWithExpectedSize(appList.size());
            for (JsonNode node: appList) {
                Map<String, Object> map = objectMapper.readValue(node, javaType);
                String pkgName = (String) map.get("package_name");
                Object tag = tagMap.get(pkgName);
                if (tag == null) {
                    continue;
                }
                map.remove("date");
                map.put("tag", tag);
                list.add(map);
            }
            if (list.size() == 0) {
                return;
            }
            outKey.set(MRUtils.JOINER.join(
                    array[0], array[1], array[2]
            ));
            outValue.set(objectMapper.writeValueAsString(list));
            context.write(outKey, outValue);
        }
    }

    @Override
    protected void otherSetting(Job job, String[] args) throws Exception {
        job.getConfiguration().set(Constants.MR_BROADCAST_STR, args[1]);
    }

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

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