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 org.apache.orc.TypeDescription;
import org.apache.orc.mapred.OrcStruct;
import org.apache.orc.mapreduce.OrcOutputFormat;

import java.io.IOException;

public class ParseInstallORCFile extends Configured implements Tool {

    public static class ConvertMapper extends Mapper<LongWritable, Text, NullWritable, OrcStruct> {
        private StringBuilder builder = new StringBuilder();
        private String dataSplit = "\t";
        private TypeDescription schema = TypeDescription
                .fromString("struct<device_id:string,device_type:string,platform:String,package_name:String,update_date:String>");
        private OrcStruct pair = (OrcStruct) OrcStruct.createValue(schema);

        @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();
                */

                pair.setFieldValue(0, new Text(splits[0]));
                pair.setFieldValue(1, new Text(splits[1]));
                pair.setFieldValue(2, new Text(splits[2]));

                JsonObject obj = null;
                try {
                    JsonArray array = GsonUtil.String2JsonArray(splits[3]);
                    for (JsonElement element : array) {
                        obj = element.getAsJsonObject();

                        /*
                        builder.setLength(0);
                        builder.append(base)
                                .append(obj.get("package_name").getAsString()).append(dataSplit)
                                .append(obj.get("date").getAsString());
                        context.write(key, new Text(builder.toString()));
                        */
                        pair.setFieldValue(3, new Text(obj.get("package_name").getAsString()));
                        pair.setFieldValue(4, new Text(obj.get("date").getAsString()));
                        context.write(NullWritable.get(), pair);
                    }
                } catch (Exception e) {
                    //  System.out.println("base = " + base + ", " + obj);
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static class ConvertReducer extends Reducer<LongWritable, Text, NullWritable, OrcStruct> {
        private String dataSplit = "\t";
        private TypeDescription schema = TypeDescription
                .fromString("struct<device_id:string,device_type:string,platform:String,package_name:String,update_date:String>");
        private OrcStruct pair = (OrcStruct) OrcStruct.createValue(schema);

        @Override
        protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            for (Text value : values) {
                String[] splits = value.toString().split(dataSplit, -1);
                if (splits.length == 5) {
                    pair.setFieldValue(0, new Text(splits[0]));
                    pair.setFieldValue(1, new Text(splits[1]));
                    pair.setFieldValue(2, new Text(splits[2]));
                    pair.setFieldValue(3, new Text(splits[3]));
                    pair.setFieldValue(4, new Text(splits[4]));
                    context.write(NullWritable.get(), pair);
                }
            }
        }
    }

    @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("orc.compress", "ZLIB");
        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.9");
        conf.set("mapreduce.map.speculative", "true");
        conf.set("mapreduce.reduce.speculative", "true");
        conf.set("orc.mapred.output.schema", "struct<device_id:string,device_type:string,platform:String,package_name:String,update_date:String>");

        //  RCFileOutputFormat.setColumnNumber(conf, 5);

        Job job = Job.getInstance(conf, "ParseInstallORCFile");
        //  job.setNumReduceTasks(Integer.parseInt(args[2]));
        job.setNumReduceTasks(0);
        job.setJarByClass(ParseInstallORCFile.class);
        job.setMapperClass(ConvertMapper.class);
        //  job.setReducerClass(ConvertReducer.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(OrcStruct.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(OrcStruct.class);
        job.setOutputFormatClass(OrcOutputFormat.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 ParseInstallORCFile(), args);
        } catch (Exception e) {
            exitCode = -1;
            e.printStackTrace();
        } finally {
            System.exit(exitCode);
        }
    }
}
