from Instagram.models import User, Picture
from Instagram.scripts.instagram_api import get_user_details, get_latest_pictures
from django.utils import timezone


def create_new_user(query):  # This creates new user in a DB
    response = get_user_details(query)

    user = User()
    user.user_name = response['username']
    user.user_id = response['id']
    user.profile_picture = response['profile_picture']

    user.save()

    return user


def remove_picture_cache(user):  # This removes all pictures associated with user passsed as a parm

    Picture.objects.filter(username_id=user.id).delete()


def update_cache(user):  # This updates time stamp for the user and loads new images, !!! should be used after removed_picture_cache
    user.cache_time = timezone.now()
    get_image_links(user)


def get_image_links(user):

    pictures = get_latest_pictures(user.user_id)

    for x in pictures:
        picture = Picture()
        picture.content = x['images']['standard_resolution']['url']
        picture.username = user
        picture.save()


def load_user(query):
    return User.objects.get(user_name=query)


def load_links(user):
    links = []

    for x in user.picture_set.all():
        links.append(x.get_url())

    return links


def generate_package(user, pictures):

    links = get_image_links(pictures, user)

    context = {
        'username': user.user_name,
        'id': user.id,
        'profile_picture': user.profile_picture,
        'urls': links
    }

    return context


def get_page(page_number):
    return 'content_%s.html' % page_number