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))

        
    def testGet(self):
        obj_buffer = ObjectsBuffer()
        user1_proxy = obj_buffer.add_object(User, None, {'name':'ed2', 'fullname':'Ed2 Jones', 'password':'edspassword'}, True)
        adress_proxy = obj_buffer.add_object(Address, None, {'user_id':user1_proxy.id,'email_address':'ed2@other.com'}, False)
        user2_proxy = obj_buffer.add_object(User, None, {'name':'ed3', 'fullname':'Ed3 Jones', 'password':'edspassword'}, True)
        obj_buffer.add_object(Address, None, {'user_id':user2_proxy.id,'email_address':'ed3@other.com'}, False)
        self.assertEquals(user1_proxy, obj_buffer.get(User, name='ed2'))
        self.assertEquals(adress_proxy, obj_buffer.get(Address, email_address='ed2@other.com'))
        self.assertEquals(user2_proxy, obj_buffer.get(User, name='ed3'))
        self.assertTrue(obj_buffer.get(User, name='ed3', fullname='Ed2 Jones') is None)

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}'
original_json_media = u'{"user": {"follow_request_sent": null, "profile_use_background_image": true, "id": 34311537, "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1452959211/63440_1494505009634_1444332638_31074099_4058882_n_normal.jpg", "profile_sidebar_fill_color": "DAECF4", "is_translator": false, "geo_enabled": false, "profile_text_color": "663B12", "followers_count": 29, "profile_sidebar_border_color": "C6E2EE", "id_str": "34311537", "default_profile_image": false, "location": "", "utc_offset": -25200, "statuses_count": 813, "description": "i like joe jonas, justin bieber, ashley tisdale, selena gomez, megen fox, kim kardashian and demi lovoto and many more.", "friends_count": 101, "profile_link_color": "1F98C7", "profile_image_url": "http://a1.twimg.com/profile_images/1452959211/63440_1494505009634_1444332638_31074099_4058882_n_normal.jpg", "notifications": null, "show_all_inline_media": false, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/298244445/tour2011.jpg", "profile_background_color": "C6E2EE", "profile_background_image_url": "http://a1.twimg.com/profile_background_images/298244445/tour2011.jpg", "name": "mikayla", "lang": "en", "profile_background_tile": true, "favourites_count": 231, "screen_name": "bieberfever17ya", "url": null, "created_at": "Wed Apr 22 16:04:28 +0000 2009", "contributors_enabled": false, "time_zone": "Mountain Time (US & Canada)", "protected": false, "default_profile": false, "following": null, "listed_count": 1}, "favorited": false, "entities": {"user_mentions": [], "media": [{"media_url_https": "https://p.twimg.com/AWea5Z-CQAAvfvK.jpg", "expanded_url": "http://twitter.com/bieberfever17ya/status/101219827649232896/photo/1", "sizes": {"small": {"h": 240, "w": 201, "resize": "fit"}, "large": {"h": 240, "w": 201, "resize": "fit"}, "medium": {"h": 240, "w": 201, "resize": "fit"}, "thumb": {"h": 150, "w": 150, "resize": "crop"}}, "url": "http://t.co/N7yZ8hS", "display_url": "pic.twitter.com/N7yZ8hS", "id_str": "101219827653427200", "indices": [31, 50], "type": "photo", "id": 101219827653427200, "media_url": "http://p.twimg.com/AWea5Z-CQAAvfvK.jpg"}], "hashtags": [], "urls": []}, "contributors": null, "truncated": false, "text": "i love you justin bieber &lt;3 http://t.co/N7yZ8hS", "created_at": "Wed Aug 10 09:14:22 +0000 2011", "retweeted": false, "in_reply_to_status_id": null, "coordinates": null, "id": 101219827649232896, "source": "web", "in_reply_to_status_id_str": null, "place": null, "in_reply_to_user_id": null, "in_reply_to_screen_name": null, "retweet_count": 0, "geo": null, "in_reply_to_user_id_str": null, "possibly_sensitive": false, "id_str": "101219827649232896"}'
original_json_media_others = u'{"user": {"utc_offset": -25200, "statuses_count": 813, "default_profile_image": false, "friends_count": 101, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/298244445/tour2011.jpg", "profile_use_background_image": true, "profile_sidebar_fill_color": "DAECF4", "profile_link_color": "1F98C7", "profile_image_url": "http://a1.twimg.com/profile_images/1452959211/63440_1494505009634_1444332638_31074099_4058882_n_normal.jpg", "time_zone": "Mountain Time (US & Canada)", "is_translator": false, "screen_name": "bieberfever17ya", "url": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "C6E2EE", "id": 34311537, "profile_background_image_url": "http://a1.twimg.com/profile_background_images/298244445/tour2011.jpg", "description": "i like joe jonas, justin bieber, ashley tisdale, selena gomez, megen fox, kim kardashian and demi lovoto and many more.", "lang": "en", "profile_background_tile": true, "favourites_count": 231, "name": "mikayla", "notifications": null, "follow_request_sent": null, "created_at": "Wed Apr 22 16:04:28 +0000 2009", "verified": false, "contributors_enabled": false, "location": "", "profile_text_color": "663B12", "followers_count": 29, "profile_sidebar_border_color": "C6E2EE", "id_str": "34311537", "default_profile": false, "following": null, "protected": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1452959211/63440_1494505009634_1444332638_31074099_4058882_n_normal.jpg", "listed_count": 1}, "favorited": false, "contributors": null, "source": "web", "text": "i love you justin bieber &lt;3 http://t.co/N7yZ8hS", "created_at": "Wed Aug 10 09:14:22 +0000 2011", "truncated": false, "retweeted": false, "in_reply_to_status_id_str": null, "coordinates": null, "in_reply_to_user_id_str": null, "entities": {"user_mentions": [], "media": [], "hashtags": [], "urls": [], "others": [{"url": "http://t.co/N7yZ8hS", "text": "comments", "indices": [31, 50]}]}, "in_reply_to_status_id": null, "in_reply_to_screen_name": null, "id_str": "101219827649232896", "place": null, "retweet_count": 0, "geo": null, "id": 101219827649232896, "possibly_sensitive": false, "in_reply_to_user_id": 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))
        entity = tweet.entity_list[0]
        self.assertEqual(u"BieberEagle", entity.user.screen_name)
        self.assertTrue(entity.user.created_at is None)
        self.assertEqual("entity_user", entity.type)
        self.assertEqual("user_mentions", entity.entity_type.label)
        

    def testTwitterProcessorMedia(self):
        tp = TwitterProcessor(None, original_json_media, 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(1, self.session.query(models.User).count())
        tweet = self.session.query(models.Tweet).first()
        self.assertFalse(tweet.user is None)
        self.assertEqual(u"mikayla",tweet.user.name)
        self.assertEqual(34311537,tweet.user.id)
        self.assertEqual(1,len(tweet.entity_list))
        entity = tweet.entity_list[0]
        self.assertEqual(101219827653427200, entity.media.id)
        self.assertEqual("photo", entity.media.type.label)
        self.assertEqual("entity_media", entity.type)
        self.assertEqual("media", entity.entity_type.label)


    def testTwitterProcessorMediaOthers(self):
        tp = TwitterProcessor(None, original_json_media_others, 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())
        tweet = self.session.query(models.Tweet).first()
        self.assertEqual(1,len(tweet.entity_list))
        entity = tweet.entity_list[0]
        self.assertEqual("entity_entity", entity.type)
        self.assertEqual("others", entity.entity_type.label)



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

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