// Created as a template for  Advanced Database Systems 2019

import java.io.*;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import org.apache.commons.logging.*;


public class SomeMapReduce_ex2a {
    public static class TextArrayWritable extends ArrayWritable {
        public TextArrayWritable(){
            super(Text.class);
        }
        public TextArrayWritable(String[] strings) {
            super(Text.class);
            Text[] texts = new Text[strings.length];
            for (int i = 0; i < strings.length; i++) {
                texts[i] = new Text(strings[i]);
            }
            set(texts);
        }
    }

    public static class MyMapper extends Mapper<Object, Text, Text, TextArrayWritable> {
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String[] result = CSVSplitter.split(value.toString());

            try{
                // format: key: author. vals: mappertype, title, checkouts
                context.write(new Text(result[7]), new TextArrayWritable(new String[]{"MyMapper", result[6].toString(), Integer.toString(Integer.parseInt(result[5]))}));
            }catch(NumberFormatException e){} // not an integer (csv header line) or no value.
        }
    }
    public static class MyOtherMapper extends Mapper<Object, Text, Text, TextArrayWritable> {
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String[] result = CSVSplitter.split(value.toString());
            // format: key: author. vals: mappertype, title, pubyear, subjects, itemlocation
            context.write(new Text(result[2]), new TextArrayWritable(new String[]{"MyOtherMapper", result[1].toString(), result[4].toString(), result[6].toString(), result[10].toString()}));
        }
    }

    public static class MyReducer extends Reducer<Text, TextArrayWritable, Text, Text> {
        private static final Log LOG = LogFactory.getLog(MyReducer.class);

        public void reduce(Text key, Iterable<TextArrayWritable> values, Context context) throws IOException, InterruptedException {
            HashMap<String,String[]> hm = new HashMap<String,String[]>();
            String[] max = new String[]{"none", "title", "0"};

            for (TextArrayWritable val : values) {
                String[] vals = val.toStrings();
                if ("MyOtherMapper".equals(vals[0])){
                    hm.put(key.toString()+"_"+vals[1], vals);
                }else{
                    if (max == null){
                        max = vals;
                        continue;
                    }
                    if (Integer.parseInt(max[2]) < Integer.parseInt(vals[2])){
                        max = vals;
                        continue;
                    }
                }
            }

            if(Integer.parseInt(max[2]) > 0 && hm.containsKey(key.toString()+"_"+max[1])) {
                String[] additionalData = hm.get(key.toString()+"_"+max[1]);
                // format: key: author. vals: title, pubyear, subjects, itemlocation
                context.write(key, new Text(max[1]+","+additionalData[1]+","+additionalData[2]+","+additionalData[3]));
            }
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf1 = new Configuration();
        conf1.set("mapreduce.output.textoutputformat.separator",",");  // This ensures that output is comma separated
        Job job = Job.getInstance(conf1);
        job.setJarByClass(SomeMapReduce_ex2a.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(TextArrayWritable.class);
        job.setReducerClass(MyReducer.class);
//    job.setNumReduceTasks(8);     // Uncomment this to run the job with more than one Reduce tasks. Depending on the system, this may produce a speedup.
        MultipleInputs.addInputPath(job, new Path(args[2]), TextInputFormat.class, MyOtherMapper.class);
        MultipleInputs.addInputPath(job, new Path(args[1]), TextInputFormat.class, MyMapper.class);
        FileOutputFormat.setOutputPath(job, new Path(args[0]));
        boolean status = job.waitForCompletion(true);
        if (status) {
            System.exit(0);
        } else {
            System.exit(1);
        }
    }
}
