import ebaysdk
import json
import requests
import random
from ebaysdk.trading import Connection as Trading
from ebaysdk.finding import Connection as Finding
from ebaysdk.shopping import Connection as Shopping
import concurrent.futures
import config as cfg
import store_ids
import ebay_api

tapi = Trading(config_file='ebay.yaml')


def revised_price(id, original_prices):
    percent = (random.randint(95, 105))/100
    rev_price = original_prices[id]*percent
    rev_price = str(round(rev_price, 2))
    return rev_price

def revise_item(id, rev_price):
    response = tapi.execute(
        'ReviseItem', {
            'item': {
            'ItemID': id,
            'StartPrice':rev_price
            }
        
        }
    )

def revise_items():
    with open('original_prices.txt') as f:
        original_prices = json.load(f)

    for id in original_prices:
        rev_price = revised_price(id, original_prices)
        revise_item(id, rev_price)

def get_prices(twenty_id):

    '''
   Gets raw JSON data from multiple live listings given multiple itemIds
    '''

    with open('temp_oauth_token.txt') as f:
        access_token = json.load(f)

    headers = {
        "X-EBAY-API-IAF-TOKEN":access_token,
        "version":"671",
        }

    url = "https://open.api.ebay.com/shopping?&callname=GetMultipleItems&responseencoding=JSON&ItemID="+twenty_id

    try:
    
        response = requests.get(url, headers=headers,timeout=24)
        response.raise_for_status()
        response = response.json()
        item = response['Item']


    except (requests.exceptions.RequestException, KeyError):
        print('connection error. IP limit possibly exceeded')
        print(response)
        return # this returns NoneType. Handled at get_prices_thread

    id_price_dict = {item['ItemID']:item['ConvertedCurrentPrice']['Value'] for item in item}
    return id_price_dict

def get_prices_thread(twenty_ids_list):
    '''
    Runs get_prices in multiple threads
    '''

    id_price_dict = {}

    with concurrent.futures.ThreadPoolExecutor() as executor:
        for future in executor.map(get_prices, twenty_ids_list):
            if future is not None:
                id_price_dict.update(future)
            else:
                print('response is None')
                break
    return id_price_dict

def main():

    with open('ebay_ids.txt') as f:
        ids = json.load(f)

    twenty_id_list = [','.join(ids[n:n+20]) for n in list(range(0,
        len(ids), 20))]

    ids = store_ids.main() # gets your store ids for all listings
    ebay_api.getAuthToken() # updates your Oauth Token
    id_price_dict = get_prices_thread(twenty_id_list)
    return id_price_dict

if __name__=="__main__":
    main()
