import os, sys
from datetime import datetime
from dateutil import relativedelta

from atproto import Client

import django
sys.path.append('../../../')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ds_events.settings'
django.setup()

from time import sleep
from pprint import pprint as ppr
import pytz

from socials.models import SocialImg
# from digitools import getBrowser, createURL, createBasicEvent, getSource

tz = pytz.timezone("US/Central")

USERNAME = "dreamfreely.org"
PASSWORD = "Futbol21!@"

client = Client()
client.login(USERNAME, PASSWORD)
feed = client.get_author_feed(USERNAME, limit = 100)

def createSocialImg(post):
    new_post, created = SocialImg.objects.update_or_create(
        uri = post['uri'],
        text = post['text'],
        img_link = post['img_link'],
        handle = post['handle'],
        created_at = post['created_at'],
        platform = 'bluesky',
    )
    print(created, new_post)

tweets = []

print(len(feed.feed))

for post in feed.feed:
    post = post.post

    # print(post, "\n\n")
    
    # try:
    #     ppr(post.embed.images[0].fullsize)
    #     # ppr(post.embed.record.record.value.text.split("\n")[:2])
    #     # ppr(post.embed.record.record.value.embed.external.uri.split("?")[0])
    #     # ppr(post.embed.record.record.uri.split("feed.post/")[1])
    # except Exception as e:
    #     print("failed:", e)

    if hasattr(post.embed, 'images'):
        p = {}
        p['img_link'] = post.embed.images[0].fullsize
        p['text'] = " ".join(post.record.text.split("\n")[:2])
        p['handle'] = post.author.handle
        p['uri'] = post.uri.split("feed.post/")[1]
        p['created_at'] = post.record.created_at

        # ppr(p)
        tweets.append(p)

        try:
            print('writing file')
            createSocialImg(p)
        except Exception as e:
            ppr(post.embed)
            print(e, "\nthis\n\n")