import tweepy
import requests
import sys, json


def send_tweet(text, image):
    is_sent = False
    consumer_key = 'vEblIuKz8mlaA6JKnLqB7Jfyr'
    consumer_secret = 'Tuzv9lTrdUVASLnEpIjONH6B6Z701u50R3t09txdQPvnwsTwpB'
    access_token = '1700043742445772800-T63s8LBqXFH1Clj0f9Q9FVuds37qIB'
    access_token_secret = 'pg7B9YAHuybro3vZEx21BCJmd3T3ANogGEBcXKbOquN4C'

    # V1 Twitter API Authentication
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)

    # Upload graph on twitter
    # Upload image to Twitter. Replace 'filename' your image filename.
    media_id = api.media_upload(filename=image,media_category='tweet_video').media_id_string
    media_id_int = int(media_id)
    # media_id = int(media_id)
    print('MEDIA ID =', media_id)
    tweet_id = 0
    if media_id_int > 0:
        print('Media Upload...Going to send the tweet')
        if sys.version_info.minor > 6:
            client = tweepy.Client(
                consumer_key=consumer_key,
                consumer_secret=consumer_secret,
                access_token=access_token,
                access_token_secret=access_token_secret
            )
            text = text.replace("\\n", "\n")
            text = text.replace("\\r", "\r")
            text = text.replace("\\", "")
            response = client.create_tweet(text=text, media_ids=[media_id])
            print(response)
            tweet_id = int(response.data['id'])
            print('TWEET ID = ', tweet_id)

            if tweet_id > 0:
                is_sent = True
        else:
            print('Old Version')
            from requests_oauthlib import OAuth1Session
            oauth = OAuth1Session(
                consumer_key,
                client_secret=consumer_secret,
                resource_owner_key=access_token,
                resource_owner_secret=access_token_secret,
            )
            payload = {"text": text, "media": {"media_ids": ["{}".format(media_id)]}}
            response = oauth.post(
                "https://api.twitter.com/2/tweets",
                json=payload,
            )
            print("Response code: {}".format(response.status_code))

            # Saving the response as JSON
            json_response = response.json()
            tweet_id = int(json_response['data']['id'])
            print(tweet_id)
            if tweet_id > 0:
                is_sent = True
            print(json.dumps(json_response, indent=4, sort_keys=True))
    return is_sent, tweet_id
