import pika, json
from app import Post, db, app

params = pika.URLParameters("amqps://govrtnay:tMnQn4JaY1ZzT3J_ErPMtABxqMMSiW9V@dingo.rmq.cloudamqp.com/govrtnay")

connection = pika.BlockingConnection(params)

channel = connection.channel()

channel.queue_declare(queue='app')

def callback(ch, method, properties, body):
    print('Received in app')
    data = json.loads(body)
    print(data)

    with app.app_context():

        if properties.content_type == 'post_created':
            post = Post(id=data['id'], title=data['title'], image=data['image'])
            db.session.add(post)
            db.session.commit()
            print('Post Created')

        elif properties.content_type == 'post_updated':
            post = Post.query.get(data['id'])
            post.title = data['title']
            post.image = data['image']
            db.session.commit()
            print('Post Updated')

        elif properties.content_type == 'post_deleted':
            post = Post.query.get(data)
            db.session.delete(post)
            db.session.commit()
            print('Post Deleted')

    channel.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(queue='app',
                      on_message_callback=callback,
                      auto_ack=False)

print('Started Consuming')

channel.start_consuming()

channel.close()


# -*- coding: utf-8 -*-
"""
Created on Fri Jul  5 01:24:52 2019

@author: Inki
"""

from threading import Thread
import tweepy
import time
import random
import keys
import log

auth = tweepy.OAuthHandler(keys.Consumer_Key_Following, keys.CONSUMER_SECRET_Following)
auth.set_access_token(keys.ACCESS_KEY_Following, keys.ACCESS_SECRET_Following)
api = tweepy.API(auth, wait_on_rate_limit=True)

class following(Thread):
    FILE_NAME = 'RTlast_seen_id.txt'
    log.log("dentro de following")

    def run(self):
        self.follow()

    def retrieve_last_seen_id(self, file_name):
        f_read = open(file_name, 'r')
        last_seen_id = int(f_read.read().strip())
        f_read.close()
        return last_seen_id

    def store_last_seen_id(self, last_seen_id, file_name):
        f_write = open(file_name, 'w')
        f_write.write(str(last_seen_id))
        f_write.close()
        return

#    def store_followrs()
#        with open('following.txt') as csv_file:
#            csv_reader = csv.reader(csv_file, delimiter=',')
#            line_count = 0
#            for row in csv_reader:
#                if line_count == 0:
#                    print(f'Column names are {", ".join(row)}')
#                    line_count += 1
#                else:
#                    print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
#                    line_count += 1
#            print(f'Processed {line_count} lines.')

    def follow(self):
        while True:
            log.log("dentro de  def follow(self):")
            last_seen_id = self.retrieve_last_seen_id(self.FILE_NAME)
#            lasttweets=api.home_timeline(since_id=last_seen_id, tweet_mode='extended', count=1)
            lasttweets=api.home_timeline(tweet_mode='extended', count=3)
            log.log(lasttweets)
            for tweet in reversed(lasttweets) :
                lista=api.user_timeline(screen_name=tweet.user.screen_name, count=10)
                log.log(lista)
                count=0
                valoraciontotal=0
                for lista in lista:
                    log.log(lista.text)
                    followers=lista.user.followers_count
                    valor=(followers)/random.randint(1,500)
                    log.log("Con {0} followers, Valor {1} para seguir a {2}".format(followers, valor, lista.user.screen_name))
                    count += 1
                    valoraciontotal+=valor

                    if valor >= 2000:
                                api.create_friendship(screen_name=lista.user.screen_name)
                                log.log("Seguido a {0}".format(lista.user.screen_name))
#                                time.sleep(random.randint(5, 120))
                                last_seen_id = tweet.id
                                self.store_last_seen_id(last_seen_id, self.FILE_NAME)
                    else:
                        log.log("No seguido a {0}".format(lista.user.screen_name))
                media=valoraciontotal/count
                log.log("Media de valores {0} para {1} muestras".format(media, count))
                last_seen_id = tweet.id
                self.store_last_seen_id(last_seen_id, self.FILE_NAME)

#
#    def follow(self):
#        while True:
#            last_seen_id = self.retrieve_last_seen_id(self.FILE_NAME)
#            lasttweets=api.home_timeline(since_id=last_seen_id, tweet_mode='extended', count=1)
#            for tweet in reversed(lasttweets) :
#


from django.views.generic import (
    FormView,
    ListView,
    DetailView,
    View
)
from django.shortcuts import render, HttpResponse
from users.models import User
from users.forms import UserForm

class UserListView(ListView):
    model = User
    template_name = 'user_list.html'

class UserDetailView(DetailView):

    model = User
    template_name = 'user_detail.html'

class AddUserView(FormView):

    form_class = UserForm
    template_name = 'form.html'
    success_url = "/"

    def form_valid(self, form):
        form.save()

        response = super().form_valid(form)

        return response

class UserEditView(View):

    def get(self, request, pk):

        form = UserForm()

        context = {
            'form': form
        }

        return render(
            template_name='form.html',
            context=context,
            request=request,
        )

    def post(self, request, pk):

        user = User.objects.get(pk=pk)

        username = request.POST['username']
        email = request.POST['email']

        if len(username) != 0:
            user.username = username

        if len(email) != 0:
            user.email = email

        user.save()

        context = {
            'user': user
        }

        return render(
            template_name='user_detail.html',
            context=context,
            request=request,
        )

class UserDeleteView(View):

    def get(self, request, pk):
        user = User.objects.get(pk=pk)
        user.delete()

        return HttpResponse(f'Deleted {user.username}')


import xlrd
import  xdrlib ,sys

def open_excel(file):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception as e:
        print(str(e))

#根据省份不同，划分成数组，提取出不同省份数据起始点
def divide_by_province(table, nrows, ncols):
    province_col = ncols - 1    #province的列数索引
    province_current = table.cell(1, province_col).value
    province_index = [1, ]
    for i in range(2, nrows-1):
        if province_current != table.cell(i, province_col).value:
            province_current = table.cell(i, province_col).value
            province_index.append(i)
    return province_index

if __name__=="__main__":
    file = 'rew_data.xlsx'  #文件路径
    bound_distance = 100    #设定在多少公里内，认为是邻近城市
    by_index = 1    #使用第二个表，如果使用第一个表，by_index=0

    data = open_excel(file)
    table = data.sheets()[by_index]
    nrows = table.nrows #行数
    ncols = table.ncols #列数
    province_index = divide_by_province(table, nrows, ncols)
    print(province_index)