package mobvista.prd.datasource.newall;

import mobvista.dmp.datasource.ga.mapreduce.vo.TextPair;
import mobvista.prd.datasource.table.MergeAppIDMR;
import mobvista.prd.datasource.tag.mapreduce.AgeTotalJob;
import mobvista.prd.datasource.util.MRUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/21 0021.
 * desc：ga，dsp，3s，m 的纯新增，idfa/gaid的纯新增
 */
public class NewAllMergeMR {
    private static final Logger log = Logger.getLogger(AgeTotalJob.class);
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        conf.set("mapreduce.job.reduce.slowstart.completedmaps", "0.5");

        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        String numReducers = otherArgs[4];
        String[] numrr = numReducers.split(",", -1);

        Job job = Job.getInstance(conf, "cross ga dsp 3s m");
        job.setJarByClass(MergeAppIDMR.class);
        job.setNumReduceTasks(Integer.parseInt(numrr[0]));
        job.setMapperClass(AllMergeMRMapper.class);
        job.setMapOutputKeyClass(TextPair.class);
        job.setMapOutputValueClass(Text.class);
        job.setReducerClass(AllMergeMRReducer.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);
        job.setGroupingComparatorClass(TextPair.FirstComparator.class);
        job.setPartitionerClass(TextPair.FirstPartitioner.class);

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

        int exitCode = job.waitForCompletion(true) ? 0 : 1;

        if (exitCode == 0) {
            Job countJob = Job.getInstance(conf, "new users count");
            countJob.setJarByClass(NewAllMergeMR.class);
            countJob.setNumReduceTasks(Integer.parseInt(numrr[1]));
            countJob.setMapperClass(CountMapper.class);
            countJob.setReducerClass(CountReducer.class);
            countJob.setMapOutputKeyClass(Text.class);
            countJob.setMapOutputValueClass(IntWritable.class);
            countJob.setOutputKeyClass(Text.class);
            countJob.setOutputValueClass(IntWritable.class);

            FileInputFormat.addInputPath(countJob, new Path(otherArgs[2]));
            FileOutputFormat.setOutputPath(countJob, new Path(otherArgs[3]));
            System.exit(countJob.waitForCompletion(true) ? 0 : 1);
        }
    }

    public static class CountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private IntWritable outVal = new IntWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            context.write(value, outVal);
        }
    }

    public static class CountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable outVal = new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable val : values) {
                count += val.get();
            }
            outVal.set(count);
            context.write(key, outVal);
        }
    }

    public static class AllMergeMRMapper extends Mapper<LongWritable, Text, TextPair, Text> {
        TextPair outKey = new TextPair();
        Text outValue = new Text();
        String todayPath = "";
        String yestdayPath = "";

        public void setup(Context context) {
            todayPath = context.getConfiguration().get("day");
            yestdayPath = context.getConfiguration().get("oldDay");
            log.info("*************************");
            log.info("* todayPath = " + todayPath);
            log.info("* yestdayPath = " + yestdayPath);
            log.info("*************************");
        }

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String dataFlag = "2";
            String line = value.toString();
            String[] fields = MRUtils.SPLITTER.split(line, -1);
            String inputFile = context.getConfiguration().get("map.input.file");
            if (inputFile.contains(todayPath)) {
                if (inputFile.contains("/3s/")) {
                    outValue.set("3s");
                } else if (inputFile.contains("/ga/")) {
                    outValue.set("ga");
                } else if (inputFile.contains("/dsp_req/")) {
                    outValue.set("dsp");
                } else if (inputFile.contains("/adn_")) {
                    outValue.set("m");
                }
            } else if (inputFile.contains(yestdayPath)) {
                dataFlag = "1";
                outValue.set(yestdayPath);
            }

            outKey.set(MRUtils.JOINER.join(fields[0], fields[1]), dataFlag);
            context.write(outKey, outValue);

        }
    }

    public static class AllMergeMRReducer extends Reducer<TextPair, Text, NullWritable, Text> {
        private Text outVal = new Text();
        public void reduce(TextPair key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            
            List<String> list = new ArrayList<String>();
            String firstVal = values.iterator().next().toString();
            if (!firstVal.contains("/")) {
                list.add(firstVal);

                for (Text val : values) {
                    list.add(val.toString());
                }

                for (String product : list) {
                    if (list.contains("ga")) {
                        outVal.set("GA");
                        context.write(NullWritable.get(), outVal);
                    }
                    if (list.contains("dsp")) {
                        outVal.set("DSP");
                        context.write(NullWritable.get(), outVal);
                    }
                    if (list.contains("m")) {
                        outVal.set("M");
                        context.write(NullWritable.get(), outVal);
                    }
                    if (list.contains("3s")) {
                        outVal.set("3S");
                        context.write(NullWritable.get(), outVal);
                    }

                    outVal.set("ALL");
                    context.write(NullWritable.get(), outVal);
                }

                String[] keySplits = MRUtils.SPLITTER.split(key.getFirst().toString(), -1);
                String deviceType = keySplits[1];
                if (deviceType.contains("idfa")) {
                    outVal.set("idfa");
                    context.write(NullWritable.get(), outVal);
                }

                if (deviceType.contains("gaid")) {
                    outVal.set("gaid");
                    context.write(NullWritable.get(), outVal);
                }
            }
        }
    }
}
