package simplejoin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

//import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
//import org.apache.hadoop.mapred.lib.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.sql.*;
import java.util.Properties;
import java.util.List;

public class simplejoin {
	
	//Mapper for the first input file
	public static class TokenizerMapper extends Mapper<LongWritable, Text, Text, Text> {
		
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
        	
	        String tokens [] = value.toString().split(",");
	        String empid = tokens[0];
	        String val = "";
	        if(tokens.length != 0)
	         {
	            for (int cnt = 1; cnt < tokens.length; cnt++){    
	               val = val + tokens[cnt] + "\t";
	            }
	        }
	        context.write(new Text(empid), new Text("inputA:"+val));
	    }
	}
	
	//Mapper for the second input file
	public static class TokenizerMapper2 extends Mapper<LongWritable, Text, Text, Text> {
		
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
	        String tokens [] = value.toString().split(",");
	        String empid = tokens[0];
	        String val = "";
	        if(tokens.length != 0)
	         {
	            for (int cnt = 1; cnt < tokens.length; cnt++){    
	               val = val + tokens[cnt] + "\t";
	            }
	        }
	        context.write(new Text(empid), new Text("inputB:"+val));
	
	    }
	}
  
	//Reducer which joins the 2 input files together
	  public static class MyReducer extends Reducer<Text, Text, Text, Text> {
		  
		  	private Splitter splitter;
		  	
		    public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
		    	splitter = Splitter.on(":").trimResults();
		    	String str = "";
	        	String inputAValue = "";
		        ArrayList<String> inputBValue = new ArrayList<String>();
		        
		        //schema of the staging table
		        for (Text val : values) {
		        	Text newVal = new Text(val);
		        	List<String> typeVal = Lists.newArrayList(splitter.split(newVal.toString()));
		        	String type = typeVal.get(0);
		        	String valStr = typeVal.get(1);
		        	
		        	
		        	if(type.equals("inputA")){
		        		inputAValue = valStr;
		        	}
		        	if(type.equals("inputB")){
		        		inputBValue.add(valStr);
		        	}
		        	if(!inputAValue.equals("") && inputBValue.size()>0){
		        		int j=0;
		        		for(String inputBVal : inputBValue){
		        			if(inputBValue.size() > 1 && j>0){
		        				str += "\n";
		        			}
		        			str += inputAValue.toString() + "\t" + inputBVal.toString();
		        			j++;
		        		}
		        		inputAValue = "";
		        		inputBValue = null;
		        	}
		        }
		        context.write(key, new Text (str));
		        	
		     }
	  }
	  

	  public static void main(String[] args) throws Exception {
	  
		    Configuration conf = new Configuration();
		    //conf.set("mapred.map.tasks", "2");
		    
		    Job job = Job.getInstance(conf, "Simplejoin");
		
		    job.setJarByClass(simplejoin.class);
		
		    
		    
		    job.setMapperClass(TokenizerMapper.class);
		    job.setReducerClass(MyReducer.class);
		
		    job.setMapOutputKeyClass(Text.class);
		    job.setMapOutputValueClass(Text.class);
		
		    job.setOutputKeyClass(Text.class);
		    job.setOutputValueClass(Text.class);
		    
		    MultipleInputs.addInputPath(job, new Path(args[0]), TextInputFormat.class,TokenizerMapper.class);
		    MultipleInputs.addInputPath(job, new Path(args[1]), TextInputFormat.class,TokenizerMapper2.class);
		
		    FileOutputFormat.setOutputPath(job, new Path(args[2]));
		
		    System.exit(job.waitForCompletion(true) ? 0 : 1);
	  }
 }