package mobvista.dmp.datasource.adn.mapreduce;

import mobvista.dmp.common.CommonMapReduce;
import mobvista.dmp.common.CommonMapper;
import mobvista.dmp.common.InstallTotalReducer;
import mobvista.dmp.util.MRUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * author: walt
 * date  : 16-11-9
 * desc  : 将etl_adn_sdk_request_daily中package_name不为空的提出出来合并到dm_install_list
 */
public class AdnSdkRequestPkgTotalMR extends CommonMapReduce {
    private static final Logger logger = LoggerFactory.getLogger(AdnSdkRequestPkgTotalMR.class);

    public static class AdnRequestPkgMapper extends CommonMapper {
        private int exceptionCount = 0;
        protected String regex = "^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$";

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            logger.info("exception count is {}", exceptionCount);
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] array = MRUtils.SPLITTER.split(value.toString(), -1);
            if (!checkDeviceId(array[0])) {
                CommonMapReduce.setMetrics(context, "DMP", "devivce_exceptions", 1);
                return;
            }

            if (array.length == 8) { //daily
                handleDaily(array, context);
            } else if (array.length == 4) { //total
                handleTotal(array, context);
            } else {
                CommonMapReduce.setMetrics(context, "DMP", "exception_Count", 1);
                exceptionCount++;
                return;
            }

            context.write(outKey, outValue);
        }


        /**
         * Handle daily. device_id device_type:idfa/gaid  platform:ios/android app_id pkg_name date
         *
         * @param array   the array
         * @param context the context
         */
        private void handleDaily(String[] array, Mapper.Context context) {
            String pkgName = array[4];
            if (pkgName.isEmpty()) {
                return;
            }
            if (array[1].equals("imei") && array[2].equals("ios")) {//过滤ios平台imei类型的数据
                return;
            }
            outKey.set(MRUtils.JOINER.join(
                    array[0], array[1], array[2]
            ));
            outValue.set(MRUtils.JOINER.join(
                    array[4], array[5]
            ));
        }

        /**
         * Handle total. device_id device_type:idfa/gaid  platform:ios/android  jsonarray:[{pkg_name,yyyy-mm}]
         *
         * @param array   the array
         * @param context the context
         */
        private void handleTotal(String[] array, Mapper.Context context) {
            outKey.set(MRUtils.JOINER.join(
                    array[0],
                    array[1],
                    array[2].toLowerCase()
            ));
            outValue.set(array[3]); //json array
        }
    }

    public static void main(String[] args) throws Exception {
        start(new AdnSdkRequestPkgTotalMR("adn req package list job", AdnRequestPkgMapper.class, InstallTotalReducer.class), args);
    }

    public AdnSdkRequestPkgTotalMR(String name, Class<? extends Mapper> mapperClass, Class<? extends Reducer> reducerClass) {
        super(name, mapperClass, reducerClass);
    }

    @Override
    protected void otherSetting(Job job, String[] args) throws Exception {
        job.setInputFormatClass(TextInputFormat.class);
    }

    @Override
    protected void setOutputPath(Job job, String[] args) throws IOException {
        FileOutputFormat.setOutputPath(job, new Path(args[2]));
        FileOutputFormat.setCompressOutput(job, true);
        FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
    }

    @Override
    protected void setInputPath(Job job, String[] args) throws IOException {
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileInputFormat.addInputPath(job, new Path(args[1]));
    }
}
