from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from pyspark.streaming.kafka import KafkaUtils
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.streaming import StreamingContext
from pyspark import  SparkConf
import redis
import sys
import os
import json
import pymysql
import numpy as np
import pandas as pd
import time
import datetime

def Json(x):
    data = json.loads(x[1])
    if 'type' in data and 'device' in data and 'params' in data and 'card_content_type' in data['params']:
        if data['type'] == 'on_click_card'and data['params']['card_content_type'] =='diary' \
                and data["device"]["device_id"] == "E417C286-40A4-42F6-BDA9-AEEBD8FEC3B6":
            return True
        # elif data['type'] == 'on_click_button'and 'params' in data:
        #     if 'page_name' in data['params'] and 'button_name' in data['params'] and 'extra_params' in data['params']:
        #         if data['params']['page_name'] =='page_choose_interest' and data['params']['button_name']=='next':
        #             return True

            return True
        else:
            return False
    else:
        return False
#queue
#rdd transform
def model(rdd):
    try:
        rdd = rdd.filter(lambda x:Json(x))
            # .repartition(10)
        return  rdd
    except:
        print("fail")

# Spark-Streaming-Kafka
sc = SparkContext(conf=SparkConf().setMaster("spark://nvwa01:7077").setAppName("filter").set("spark.io.compression.codec", "lzf"))
ssc=SQLContext(sc)
ssc = StreamingContext(sc,4)
sc.setLogLevel("WARN")
kafkaParams = {"metadata.broker.list": "172.16.44.25:9092,172.16.44.31:9092,172.16.44.45:9092",
               "group.id": "filter",
               "socket.timeout.ms": "600000",
               "auto.offset.reset": "largest"}


stream = KafkaUtils.createDirectStream(ssc, ["gm-maidian-data"], kafkaParams)
transformstream = stream.transform(lambda x:model(x))
transformstream.pprint()
ssc.start()
ssc.awaitTermination()