import random
import time

from includes import api
from includes import helpers
from includes.wordpress import wordpress as wp
from urllib.parse import urlparse, urlunparse

posts = helpers.read_json_file('posts')
overrides = helpers.read_json_file('overrides')

for post_id, args in list(overrides.items()):

    post_info = api.get_post_override(post_id, args)

    if 'post_id' not in post_info:
        continue

    del overrides[post_id]
    helpers.save_json_file('overrides', overrides)

    posts[post_id] = post_info

    helpers.save_json_file('posts', posts)

merged_posts = helpers.merge_post_data_by_imdb(posts)

for post_info in merged_posts:

    if not post_info['download_links']:
        continue

    if post_info['trailer']:
        parsed = urlparse(post_info['trailer'])
        clean_url = urlunparse((parsed.scheme, parsed.netloc, parsed.path, '', '', ''))
        post_info['trailer'] = clean_url

    res = wp.update_create_post(post_info)

    print(res)

    time.sleep(random.uniform(4.5, 5.5))

print('process finished.')
