from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
import unittest #@UnresolvedImport
from sqlalchemy.orm import sessionmaker
from iri_tweet.utils import ObjectsBuffer, TwitterProcessor
from iri_tweet import models
import tempfile #@UnresolvedImport
import os

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
    
    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password
    
    def __repr__(self):
        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)


class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))
    
    user = relationship("User", backref=backref('addresses', order_by=id))
    
    def __init__(self, user_id, email_address):
        self.email_address = email_address
        self.user_id = user_id
    
    def __repr__(self):
        return "<Address('%s')>" % self.email_address



class TestObjectBuffer(unittest.TestCase):
    
    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:', echo=False)
        Base.metadata.create_all(self.engine)
        sessionMaker = sessionmaker(bind=self.engine)
        self.session = sessionMaker()

    def tearDown(self):
        self.session.close()
        self.engine.dispose()

        
    def testCreateUser(self):
        ed_user = User('ed', 'Ed Jones', 'edspassword')
        self.session.add(ed_user)
        self.assertTrue(ed_user.id is None)
        self.session.commit()
        self.assertTrue(ed_user.id is not None)

        
    def testSimpleBuffer(self):
        obj_buffer = ObjectsBuffer()
        obj_proxy = obj_buffer.add_object(User, ['ed1', 'Ed1 Jones', 'edspassword'], None, False)
        self.assertTrue(obj_proxy.id() is None)
        obj_buffer.persists(self.session)
        self.assertTrue(obj_proxy.id() is None)
        self.session.commit()
        self.assertTrue(obj_proxy.id() is not None)


    def testSimpleBufferKwargs(self):
        obj_buffer = ObjectsBuffer()
        obj_proxy = obj_buffer.add_object(User, None, {'name':'ed1b', 'fullname':'Ed1b Jones', 'password':'edspassword'}, False)
        self.assertTrue(obj_proxy.id() is None)
        obj_buffer.persists(self.session)
        self.assertTrue(obj_proxy.id() is None)
        self.session.commit()
        self.assertTrue(obj_proxy.id() is not None)

        
    def testSimpleBufferFlush(self):
        obj_buffer = ObjectsBuffer()
        obj_proxy = obj_buffer.add_object(User, ['ed2', 'Ed2 Jones', 'edspassword'], None, True)
        self.assertTrue(obj_proxy.id() is None)
        obj_buffer.persists(self.session)
        self.assertTrue(obj_proxy.id() is not None)
        self.session.commit()
        self.assertTrue(obj_proxy.id() is not None)
        
    def testRelationBuffer(self):
        obj_buffer = ObjectsBuffer()
        user1_proxy = obj_buffer.add_object(User, ['ed3', 'Ed3 Jones', 'edspassword'], None, True)
        obj_buffer.add_object(Address, [user1_proxy.id,'ed3@mail.com'], None, False)
        obj_buffer.add_object(Address, [user1_proxy.id,'ed3@other.com'], None, False)
        user2_proxy = obj_buffer.add_object(User, ['ed4', 'Ed3 Jones', 'edspassword'], None, True)
        obj_buffer.add_object(Address, [user2_proxy.id,'ed4@mail.com'], None, False)
        obj_buffer.persists(self.session)
        self.session.commit()
        ed_user = self.session.query(User).filter_by(name='ed3').first()
        self.assertEquals(2, len(ed_user.addresses))
        ed_user = self.session.query(User).filter_by(name='ed4').first()
        self.assertEquals(1, len(ed_user.addresses))

        

original_json = u'{"in_reply_to_user_id_str":null,"text":"RT @BieberEagle: \\"I love my haters. They spend so much time thinking about me. Aren\u2019t they sweet?\\" - Justin Bieber","contributors":null,"retweeted":false,"coordinates":null,"retweeted_status":{"in_reply_to_user_id_str":null,"text":"\\"I love my haters. They spend so much time thinking about me. Aren\u2019t they sweet?\\" - Justin Bieber","contributors":null,"retweeted":false,"coordinates":null,"retweet_count":"100+","source":"web","entities":{"user_mentions":[],"hashtags":[],"urls":[]},"truncated":false,"place":null,"id_str":"96638597737889792","in_reply_to_user_id":null,"in_reply_to_status_id":null,"favorited":false,"in_reply_to_status_id_str":null,"user":{"is_translator":false,"profile_background_tile":true,"profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/298443445\/355584171.jpg","listed_count":5040,"friends_count":8477,"profile_link_color":"ff0000","profile_sidebar_border_color":"000000","url":"http:\/\/twitpic.com\/photos\/BieberEagle","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1465491672\/355584171_normal.jpg","profile_image_url":"http:\/\/a2.twimg.com\/profile_images\/1465491672\/355584171_normal.jpg","description":"1 name, 1 inspiration, 1 hero, 1 smile, 1 singer, 1 boy who changed my life.    B.\u0130.E.B.E.R-Believe In Everything Because Everything\'s Reachable. #NEVERSAYNEVER","default_profile":false,"notifications":null,"time_zone":"Paris","followers_count":14506,"default_profile_image":false,"lang":"en","profile_use_background_image":true,"screen_name":"BieberEagle","show_all_inline_media":false,"geo_enabled":false,"profile_background_color":"ffffff","location":"\u2665 Albania \u2665 ","id_str":"229067923","profile_background_image_url":"http:\/\/a2.twimg.com\/profile_background_images\/298443445\/355584171.jpg","favourites_count":89,"protected":false,"follow_request_sent":null,"following":null,"name":"truebelieber","statuses_count":24279,"verified":false,"created_at":"Tue Dec 21 12:35:18 +0000 2010","profile_text_color":"000000","id":229067923,"contributors_enabled":false,"utc_offset":3600,"profile_sidebar_fill_color":""},"id":96638597737889792,"created_at":"Thu Jul 28 17:50:11 +0000 2011","geo":null,"in_reply_to_screen_name":null},"retweet_count":"100+","source":"web","entities":{"user_mentions":[{"indices":[3,15],"screen_name":"BieberEagle","id_str":"229067923","name":"truebelieber","id":229067923}],"hashtags":[],"urls":[]},"truncated":false,"place":null,"id_str":"96965037637382145","in_reply_to_user_id":null,"in_reply_to_status_id":null,"favorited":false,"in_reply_to_status_id_str":null,"user":{"is_translator":false,"profile_background_tile":true,"profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/300419382\/ipod.7.14_054.JPG","listed_count":3,"friends_count":1150,"profile_link_color":"00cccc","profile_sidebar_border_color":"c8ff00","url":"http:\/\/www.facebook.com\/blovedbecca180","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1466752962\/block_party_7.27.11_015_normal.JPG","profile_image_url":"http:\/\/a3.twimg.com\/profile_images\/1466752962\/block_party_7.27.11_015_normal.JPG","description":"if ya wanna know something about me, then get to know me. \\n\\r\\n\\ri promise, you wont regret it. (:\\r\\ni love justin bieber with an extreme burning passion!","default_profile":false,"notifications":null,"time_zone":"Central Time (US & Canada)","followers_count":361,"default_profile_image":false,"lang":"en","profile_use_background_image":true,"screen_name":"beccaxannxx","show_all_inline_media":false,"geo_enabled":false,"profile_background_color":"ff0066","location":"","id_str":"65624607","profile_background_image_url":"http:\/\/a3.twimg.com\/profile_background_images\/300419382\/ipod.7.14_054.JPG","favourites_count":266,"protected":false,"follow_request_sent":null,"following":null,"name":"beccaxannxx","statuses_count":2512,"verified":false,"created_at":"Fri Aug 14 12:36:35 +0000 2009","profile_text_color":"6a39d4","id":65624607,"contributors_enabled":false,"utc_offset":-21600,"profile_sidebar_fill_color":"ff00bb"},"id":96965037637382145,"created_at":"Fri Jul 29 15:27:21 +0000 2011","geo":null,"in_reply_to_screen_name":null}'


class TestTwitterProcessor(unittest.TestCase):
    
    def setUp(self):
        self.engine, self.metadata = models.setup_database('sqlite:///:memory:', echo=True)
        sessionMaker = sessionmaker(bind=self.engine)
        self.session = sessionMaker()
        file, self.tmpfilepath = tempfile.mkstemp()
        os.close(file)


    def testTwitterProcessor(self):
        tp = TwitterProcessor(None, original_json, None, self.session, self.tmpfilepath)
        tp.process()
        self.session.commit()
        
        self.assertEquals(1, self.session.query(models.TweetSource).count())
        self.assertEquals(1, self.session.query(models.Tweet).count())
        self.assertEquals(2, self.session.query(models.User).count())
        tweet = self.session.query(models.Tweet).first()
        self.assertFalse(tweet.user is None)
        self.assertEqual(u"beccaxannxx",tweet.user.name)
        self.assertEqual(65624607,tweet.user.id)
        self.assertEqual(1,len(tweet.entity_list))
        self.assertEqual(u"BieberEagle", tweet.entity_list[0].user.screen_name)


    def tearDown(self):
        self.session.close()
        self.engine.dispose()
        os.remove(self.tmpfilepath)

if __name__ == '__main__':
    unittest.main()