package mobvista.dmp.main;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mobvista.dmp.format.RCFileOutputFormat;
import mobvista.dmp.util.BytesRefUtil;
import mobvista.prd.datasource.util.GsonUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
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.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParseInstallRCFile extends Configured implements Tool {

    public static class ConvertMapper extends Mapper<LongWritable, Text, LongWritable, BytesRefArrayWritable> {
        private StringBuilder builder = new StringBuilder();
        private String dataSplit = "\t";

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split(dataSplit, -1);
            if (splits.length >= 4) {
                builder.setLength(0);
                builder.append(splits[0]).append(dataSplit)
                        .append(splits[1]).append(dataSplit)
                        .append(splits[2]).append(dataSplit);
                String base = builder.toString();

                JsonObject obj = null;
                try {
                    JsonArray array = GsonUtil.String2JsonArray(splits[3]);
                    for (JsonElement element : array) {
                        obj = element.getAsJsonObject();
                        String package_name=obj.get("package_name").getAsString();
                        Pattern idiosPtn = Pattern.compile("^id\\d+$");
                        Matcher midios = idiosPtn.matcher(package_name);
                        if( splits[2].equals("ios") && midios.find() ){
                            package_name = midios.group(0).replace("id", "");
                        }
                        builder.setLength(0);
                        builder.append(base)
                                .append(package_name).append(dataSplit)
                                .append(obj.get("date").getAsString());
                        context.write(key, BytesRefUtil.createRcOutValue(builder.toString()));
                    }
                } catch (Exception e) {
                    System.out.println("base = " + base + ", " + obj);
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static class ConvertReducer extends Reducer<LongWritable, BytesRefArrayWritable, NullWritable, BytesRefArrayWritable> {
        @Override
        protected void reduce(LongWritable key, Iterable<BytesRefArrayWritable> values, Context context) throws IOException, InterruptedException {
            for (BytesRefArrayWritable brfw : values) {
               context.write(NullWritable.get(), brfw);
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.setBoolean("mapreduce.output.fileoutputformat.compress", true);
        conf.set("mapreduce.output.fileoutputformat.compress.type",
                SequenceFile.CompressionType.BLOCK.toString());
        conf.setClass("mapreduce.output.fileoutputformat.compress.codec",
                GzipCodec.class, CompressionCodec.class);
        conf.set("mapreduce.job.reduce.slowstart.completedmaps", "0.7");
        conf.set("mapreduce.map.speculative", "true");
        conf.set("mapreduce.reduce.speculative", "true");

        RCFileOutputFormat.setColumnNumber(conf, 5);

        Job job = Job.getInstance(conf, "ParseInstallRCFile");
        job.setNumReduceTasks(Integer.parseInt(args[2]));
        job.setJarByClass(ParseInstallRCFile.class);
        job.setMapperClass(ConvertMapper.class);
        job.setReducerClass(ConvertReducer.class);
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(BytesRefArrayWritable.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(BytesRefArrayWritable.class);
        job.setOutputFormatClass(RCFileOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // job.addFileToClassPath(new Path("s3://mob-emr-test/feng.liang/lib/hive-exec-0.13.1-amzn-3.jar"));
         job.addFileToClassPath(new Path("s3://mob-emr-test/dataplatform/env/hive/lib/hive-exec-2.3.3.jar"));


        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) {
        int exitCode = 0;
        try {
            exitCode = ToolRunner.run(new Configuration(), new ParseInstallRCFile(), args);
        } catch (Exception e) {
            exitCode = -1;
            e.printStackTrace();
        } finally {
            System.exit(exitCode);
        }
    }
}
