# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 10:48:32 2017

export short video data according to 融合传播指数-短视频账号列表.csv

Nov 13 2017
Xin Yue found that, there are some videos missed by the value of 'video_number_of_the_day'.
For example, TV column '深视新闻' has released some videos on Sep 22 2017 on platform 央视新闻+,
but they are absent in data file '短视频明细_2017-09-23.csv', while present in 
data file '短视频明细_2017-09-24.csv', and the fetch_time are around Sep 24 2017.
That means, they are missed when our date provider crawl the platform on Sep 23,
while catched on Sep 24. (If they are still missed on Sep 24 and forever, we won't
be able to discover this issue by only checking the data.) 
To solve this, the exporting program will search the database rather than only 
summarize the detailed output file. A field 'video_number_of_the_day_global' will
be added on the summarizing file to hold the searched values.

@author: hanye
"""
#from esCCR import EsUtils
import datetime, time
import pandas as pd
from elasticsearch.helpers import scan
import elasticsearch
import sys
import copy
import func_scp_py
from scp import SCPException
import logging, importlib


todayT=datetime.datetime.now()
#yesterdayT=todayT-datetime.timedelta(days=1)
one_d_bfr_yesterdayT=todayT-datetime.timedelta(days=2)
two_d_bfr_yesterdayT=todayT-datetime.timedelta(days=3)

# define logger
logger=logging.getLogger('short_video_for_CCI')
logger.setLevel(logging.INFO)
# create handler
path='/home/hanye/project_data/Python/Projects/CCI/log/'
log_fn='export_CCI_short_video_data_on_%s_log' % (datetime.datetime.now().isoformat().replace(':','-')[:23])
fh=logging.FileHandler(path+log_fn)
fh.setLevel(logging.INFO)
# create formatter and add it to the handler
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# add handler to logger
logger.addHandler(fh)

logger.info('************ log starts')

hosts='192.168.17.11'
port=9200
user='elastic'
passwd='hy_csm_16'
http_auth=(user, passwd)

es=elasticsearch.Elasticsearch(hosts=hosts, port=port, http_auth=http_auth)

index='short-video-production'
doc_type_daily_url='daily-url'
doc_type_all_time_url='all-time-url'

# 1 build {platform:releaser} dict of interest

resource_path = '/home/hanye/project_data/Python/Projects/CCI/resource/'
releaser_mapping_filename = '融合传播指数-短视频账号列表.csv'

TV_column_dict = {}
TV_column_Lst=[]

f_releaser_mapping = open(resource_path+releaser_mapping_filename, 'r', encoding='gb18030')
header = f_releaser_mapping.readline().strip().split(',')
for line in f_releaser_mapping:
    line_Lst = line.strip().split(',')
    line_dict = dict(zip(header, line_Lst))
    TV_column_Lst.append(line_dict)

f_releaser_mapping.close()


for line in TV_column_Lst:
    TV_column_name=line['栏目']
    for plt in line:
        if plt not in ['序号', '栏目']:
            if line[plt]!='':
                if TV_column_name not in TV_column_dict:
                    TV_column_dict[TV_column_name]={plt: [line[plt]]}
                elif plt not in TV_column_dict[TV_column_name]:
                    TV_column_dict[TV_column_name][plt]=[line[plt]]
                else:
                    TV_column_dict[TV_column_name][plt].append(line[plt])


platform_releaser_dict = {} 
for column in TV_column_dict:
    for platform in TV_column_dict[column]:
        if platform not in platform_releaser_dict:
            platform_releaser_dict.update({platform: copy.deepcopy(TV_column_dict[column][platform])})
        else:
            releaser_Lst = platform_releaser_dict[platform]
            releaser_Lst += TV_column_dict[column][platform]
            releaser_Lst = list(set(releaser_Lst))
            if '' in releaser_Lst:
                releaser_Lst.remove('')
            platform_releaser_dict[platform] = releaser_Lst


releaser_TV_column_dict = {}
for TV_column in TV_column_dict:
    for platform in TV_column_dict[TV_column]:
        for releaser in TV_column_dict[TV_column][platform]:
            if releaser not in releaser_TV_column_dict:
                releaser_TV_column_dict.update({releaser: TV_column})
            else:
                logger.info('duplicated releaser name: %s' % releaser)


# 2 export short video data from ccr es according to {platform:releaser} dict
def export_short_video_data(dayT):
    search_body={
            "query": {
                    "bool": {
                            "filter": [
                                    {"range": {"release_time": {"gte":0, "lte":0}}},
                                    {"range": {"fetch_time": {"gte":0, "lte":0}}},
                                    {"term": {"platform.keyword": None}},
                                    {"term": {"releaser.keyword": None}}
                                    ],
                            }
                    }
            }
    
    
    survey_date_T=datetime.datetime(dayT.year, dayT.month, dayT.day)
    survey_date=survey_date_T.isoformat()[:10]
    
    release_time_start_T = survey_date_T - datetime.timedelta(days=15)
    release_time_start_iso = release_time_start_T.isoformat()
    release_time_end_iso = survey_date_T.isoformat()
    
    fetch_time_start_T = survey_date_T + datetime.timedelta(seconds=0)
    fetch_time_start_iso = fetch_time_start_T.isoformat()
    fetch_time_end_T = survey_date_T + datetime.timedelta(seconds=24*3600-1)
    fetch_time_end_iso = fetch_time_end_T.isoformat()
    
    release_time_start_ts=int(datetime.datetime
                           .strptime(release_time_start_iso, '%Y-%m-%dT%H:%M:%S')
                           .timestamp()*1000)
    release_time_end_ts=int(datetime.datetime
                           .strptime(release_time_end_iso, '%Y-%m-%dT%H:%M:%S')
                           .timestamp()*1000)
    
    fetch_time_start_ts=int(datetime.datetime
                           .strptime(fetch_time_start_iso, '%Y-%m-%dT%H:%M:%S')
                           .timestamp()*1000)
    fetch_time_end_ts=int(datetime.datetime
                           .strptime(fetch_time_end_iso, '%Y-%m-%dT%H:%M:%S')
                           .timestamp()*1000)
    
    search_body['query']['bool']['filter'][0]['range']['release_time']['gte']=release_time_start_ts
    search_body['query']['bool']['filter'][0]['range']['release_time']['lte']=release_time_end_ts
    search_body['query']['bool']['filter'][1]['range']['fetch_time']['gte']=fetch_time_start_ts
    search_body['query']['bool']['filter'][1]['range']['fetch_time']['lte']=fetch_time_end_ts
    
    data_raw_collector = [] 
    
    for platform in platform_releaser_dict:
        search_body['query']['bool']['filter'][2]['term']['platform.keyword']=platform
        logger.info('platform %s' % platform)
        for releaser in platform_releaser_dict[platform]: 
            logger.info('platform %s, releaser %s' % (platform, releaser))
            search_body['query']['bool']['filter'][3]['term']['releaser.keyword']=releaser
            search_re=es.search(index=index,
                         doc_type=doc_type_daily_url,
                         body=search_body,
                         size=10,
                         request_timeout=100)
            total_hits=search_re['hits']['total']
            logger.info('platform %s, releaser %s total hits: %d' % (platform, releaser, total_hits))
            scan_re=scan(client=es, 
                         index=index,
                         doc_type=doc_type_daily_url,
                         query=search_body,
                         size=1000,scroll='5m',
                         request_timeout=100)
            line_counter=0
            for line in scan_re:
                line_dict=line
                data_raw_collector.append(line_dict)
                line_counter+=1
                if line_counter%1000==0 or line_counter==total_hits:
                    logger.info('processing line %d/%d' % (line_counter, total_hits))
                
    
    columns = ['url', 'data_provider', 'platform', 'duration', 'title',
               'release_time_H', 'releaser', 'TV_column',
               'net_inc_play_count','net_inc_play_count_wiped_flag','net_inc_play_count_original',
               'net_inc_comment_count','net_inc_comment_count_wiped_flag','net_inc_comment_count_original',
               'net_inc_favorite_count','net_inc_favorite_count_wiped_flag','net_inc_favorite_count_original',
               'play_count', 'comment_count', 'favorite_count',
               'fetch_time_H']
    data_Lst= []
    
    for line in data_raw_collector:
        line_dict=line['_source']
        data_dict = {}
        for col in columns:
            if col not in line_dict:
                line_dict.update({col: ''})
            if col not in ['TV_column', 'release_time_H', 'fetch_time_H']:
                data_dict.update({col: line_dict[col]})
        
        release_time_ts = line_dict['release_time']/1e3
        fetch_time_ts = line_dict['fetch_time']/1e3
        release_time_H = datetime.datetime.fromtimestamp(release_time_ts).isoformat()
        fetch_time_H = datetime.datetime.fromtimestamp(fetch_time_ts).isoformat()
        
        releaser = line_dict['releaser']
        TV_column = releaser_TV_column_dict[releaser]
        data_dict.update({'release_time_H': release_time_H, 
                          'fetch_time_H': fetch_time_H,
                          'TV_column': TV_column})
        
        # negative daily net_inc values will be wiped to zero, leaving a modify flag
        # added on Oct 17 2017
        net_inc_play_count=data_dict['net_inc_play_count']
        if net_inc_play_count!='' and int(net_inc_play_count)<0:
            net_inc_play_count_wiped_flag=True
            net_inc_play_count_original=net_inc_play_count
            net_inc_play_count=0
            data_dict.update({'net_inc_play_count': net_inc_play_count,
                              'net_inc_play_count_wiped_flag': net_inc_play_count_wiped_flag,
                              'net_inc_play_count_original': net_inc_play_count_original, })           
            
        net_inc_comment_count=data_dict['net_inc_comment_count']
        if net_inc_comment_count!='' and int(net_inc_comment_count)<0:
            net_inc_comment_count_wiped_flag=True
            net_inc_comment_count_original=net_inc_comment_count
            net_inc_comment_count=0
            data_dict.update({
                              'net_inc_comment_count': net_inc_comment_count,
                              'net_inc_comment_count_wiped_flag': net_inc_comment_count_wiped_flag,
                              'net_inc_comment_count_original': net_inc_comment_count_original,  })      
        
        net_inc_favorite_count=data_dict['net_inc_favorite_count']
        if net_inc_favorite_count!='' and int(net_inc_favorite_count)<0:
            net_inc_favorite_count_wiped_flag=True
            net_inc_favorite_count_original=net_inc_favorite_count
            net_inc_favorite_count=0
            data_dict.update({
                              'net_inc_favorite_count': net_inc_favorite_count,
                              'net_inc_favorite_count_wiped_flag': net_inc_favorite_count_wiped_flag,
                              'net_inc_favorite_count_original': net_inc_favorite_count_original,
                              })
        
        data_Lst.append(data_dict)
    
    data_path='/home/hanye/project_data/Python/Projects/CCI/data/'    
    data_df = pd.DataFrame(data=data_Lst, columns=columns)
    csv_fn_details=data_path+'短视频明细'+survey_date.replace('-','')+'.csv'
    data_df.to_csv(csv_fn_details,
                   index=False, encoding='gb18030',)
    
    TV_column_summary_dict = {}    
    release_date_according_to_survey_date = (survey_date_T-datetime.timedelta(days=1)).isoformat()[:10]
    
    for TV_column in TV_column_dict:
        TV_column_summary_dict.update({TV_column: {
                                                    'video_number_of_the_day': 0,
                                                    # add a global value of video number for a releaser
                                                    # Nov 13 2017
                                                    'video_number_of_the_day_global': 0,
                                                    'play_count_of_recent_15_days': 0,
                                                    'comment_count_of_recent_15_days': 0,
                                                    'favorite_count_of_recent_15_days': 0,
                                                    }})
        
    for line in data_Lst:
        if line['net_inc_play_count']=='':
            line['net_inc_play_count']=0
        if line['net_inc_comment_count']=='':
            line['net_inc_comment_count']=0
        if line['net_inc_favorite_count']=='':
            line['net_inc_favorite_count']=0
        
        TV_column_summary_dict[line['TV_column']]['play_count_of_recent_15_days'] += int(line['net_inc_play_count'])
        TV_column_summary_dict[line['TV_column']]['comment_count_of_recent_15_days'] += int(line['net_inc_comment_count'])
        TV_column_summary_dict[line['TV_column']]['favorite_count_of_recent_15_days'] += int(line['net_inc_favorite_count'])
        release_time_H = line['release_time_H']
        release_time_day_str = release_time_H[:10]
        if release_time_day_str==release_date_according_to_survey_date:
            TV_column_summary_dict[line['TV_column']]['video_number_of_the_day'] += 1
    
    # search global video_num for a TV column
    # Nov 13 2017
    release_date_according_to_survey_date_T=survey_date_T-datetime.timedelta(days=1)
    target_release_time_ts_start=int(release_date_according_to_survey_date_T.timestamp()*1e3)
    target_release_time_ts_end=int(survey_date_T.timestamp()*1e3-1)
    for TV_col in TV_column_summary_dict:
        for platform_target in TV_column_dict[TV_col]:
            releaser_target_Lst=TV_column_dict[TV_col][platform_target]
            for releaser_target in releaser_target_Lst:
                if releaser_target!='':
                    search_for_video_num_globally_body={
                            "query": {
                                    "bool": {
                                            "filter": [
                                                    {"range": {"release_time": {"gte":target_release_time_ts_start,
                                                                                "lte":target_release_time_ts_end}}},
                                                    {"term": {"platform.keyword": platform_target}},
                                                    {"term": {"releaser.keyword": releaser_target}}
                                                    ]
                                            }
                                    },
                            "size": 0
                            }
                    search_for_video_num_globally_resp=es.search(index=index,
                                                                 doc_type=doc_type_all_time_url,
                                                                 body=search_for_video_num_globally_body,
                                                                 request_timeout=100)
                    global_search_hit=search_for_video_num_globally_resp['hits']['total']
                    TV_column_summary_dict[TV_col]['video_number_of_the_day_global']+=global_search_hit
    
    columns_summary = ['TV_column',
                        # add a global value of video number for a releaser
                        # Nov 13 2017                       
                       'video_number_of_the_day_global',
                       'play_count_of_recent_15_days',
                       'comment_count_of_recent_15_days',
                       'favorite_count_of_recent_15_days',
                       'video_number_of_the_day']
    
    TV_column_summary_Lst = []
    for TV_column in TV_column_summary_dict:
        line_dict = TV_column_summary_dict[TV_column]
        line_dict.update({'TV_column': TV_column})
        TV_column_summary_Lst.append(line_dict)
    
    TV_column_summary_df = pd.DataFrame(data=TV_column_summary_Lst, columns=columns_summary)
    csv_fn_summary=data_path+'短视频汇总'+survey_date.replace('-', '')+'.csv'
    TV_column_summary_df.to_csv(csv_fn_summary,
                                index=False, encoding='gb18030')
    
    return (csv_fn_summary, csv_fn_details)



logger.info('****** exporting data for %s ******' % one_d_bfr_yesterdayT)
ystd_summary, ystd_detail = export_short_video_data(one_d_bfr_yesterdayT)
logger.info('exporting data for %s done' % one_d_bfr_yesterdayT)

logger.info('****** exporting data for %s ******' % two_d_bfr_yesterdayT)
d_bfr_ystd_summary, d_bfr_ystd_detail = export_short_video_data(two_d_bfr_yesterdayT)
logger.info('exporting data for %s done' % two_d_bfr_yesterdayT)


# 3 scp exported csv files onto FTP server
local_data_path='/home/hanye/project_data/Python/Projects/CCI/data'
remote_full_path='/boot/opt/ccr/CCI/daily_export'
scp_sucessed_flag=False
scp_start_T=datetime.datetime.now()
while not scp_sucessed_flag:
    # if wait for more than 24 hours, program will exit
    if (datetime.datetime.now()-scp_start_T).total_seconds()>24*3600:
        logger.info('Have waited for more than 24 hours, program will exit.')
        sys.exit(0)
    
    try:
        logger.info('****** start scp from local %s to ftp server %s' % (local_data_path, remote_full_path))
        t_s = datetime.datetime.now()
        
        func_scp_py.scp_to_ftp_server(ystd_summary, remote_full_path)
        logger.info('scp %s done.' % ystd_summary)
        
        func_scp_py.scp_to_ftp_server(ystd_detail, remote_full_path)
        logger.info('scp %s done.' % ystd_detail)
        
        func_scp_py.scp_to_ftp_server(d_bfr_ystd_summary, remote_full_path)
        logger.info('scp %s done.' % d_bfr_ystd_summary)
        
        func_scp_py.scp_to_ftp_server(d_bfr_ystd_detail, remote_full_path)
        logger.info('scp %s done.' % d_bfr_ystd_detail)
        
    except SCPException:
        logger.info('catched SCPException, no file copyed, will try again.')
        importlib.reload(func_scp_py)  # reload is necessary for scp retry
        time.sleep(300)
    else:
        scp_sucessed_flag=True
        t_e = datetime.datetime.now()
        t_delta = t_e - t_s
        logger.info('scp done, time spent %s' % t_delta)

logger.info('All done.')
