# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login


import json
import time
import os
import re

from logger import Logger
from worker import Worker
from django_datastore import *
from instabot import Bot


from shopapp.serializers import *


insta_login = 'studio_7_day_2'
insta_password = 'Nopasaran'


def get_base_dir():
    return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

worker = Worker(insta_login, insta_password)
logger = Logger('view')
time_now = time.strftime('%X %x').replace(' ', '_').replace('/', '_').replace(':', '_')


#@login_required
def main(request):
    return render(request, 'studio/test_front.html', {})


def n_user(request):
    if request.method == 'GET':
        return render(request, 'studio/login.html', {})
    else:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            print 'OK'



def insta_shop(request):
    # View for update InstaShopItem list.
    logger.log(str(request))

    shop_page_name = 'studio_7_day_2'
    tag  = '#minimal'

    tag_regex      = re.compile(r'#\S+')
    price_regex    = re.compile(r'(?i)(?P<price>(?:цена|price) *:* *\d+)')
    category_regex = re.compile(tag + '_(\S+)')
    name_regex     = re.compile(r'(?i)(?P<name>^.+?\.)')

    author = get_user_from_database(user_name = shop_page_name)

    if not author:
        bot = Bot()
        user_info = bot.get_info(shop_page_name, loggined = False)

        author = create_update_user(user_info)


    # Get all medias from user's page
    medias = worker.get_medias(shop_page_name)


    logger.log('Medias: ' + str(medias))

    for media in medias:
        try:
            logger.log(shop_page_name)
            author = InstaUser.objects.get(user_name = shop_page_name)
        except Exception as e:
            logger.log(str(e))

        caption = media['caption']

        if media['is_video']== True:
            continue

        if tag not in media['caption']:
            continue


        # Create a new InstaMedia if ir doesn't exists
        try:
            media_instance = InstaMedia.objects.get(image_id = media['id'])
        except:

            media_instance = InstaMedia(image_id  = media['id'],
                               caption            = caption,
                               image_author       = author,
                               likes_count = media['likes']['count'],
                               code               = media['code']
                               )

            media_instance.save()

            # Get src(-s)
            for src in media['srcs']:
                logger.log('SRC: ' + src)
                try:
                    src_instance = InstaMediaSRC.objects.get(media_src = src)
                except:
                    logger.log('Create InstaMediaSRC: ' + src)
                    src_instance = InstaMediaSRC(media_src   = src,
                                                 insta_media = media_instance)
                    src_instance.save()




        try:
            item = InstaShopItem.objects.get(media = media_instance)
        except:

            price = 'No price'
            category = 'main'
            item_name = ''

            name_search = re.search(name_regex, caption)
            if name_search:
                name = name_search.group('name')

            category_search = re.search(category_regex, caption)
            if category_search:
                category = category_search.group(1)


            price_search = re.search(price_regex, caption)
            if price_search:
                price = price_search.group('price')
                caption = caption.replace(price, '')

            tags_search = re.findall(tag_regex, caption)
            if tags_search:
                logger.log(tags_search)
                for tag in tags_search:
                    caption = caption.replace(str(tag), '')

            item = InstaShopItem(name = item_name,
                                 media = media_instance,
                                 price = price,
                                 description = caption,
                                 category = category)
            item.save()


    all_media = InstaMedia.objects.filter(image_author__user_name = shop_page_name)
    for media in all_media:
        media_info = worker.get_media_info(code = media.code)
        logger.log(media_info['status_code'])
        if media_info['status_code'] != 200:
            media.delete()

    return render(request, 'studio/insta_shop.html', {})



def api_test(request):
    return render(request, 'studio/api_test.html',{})


def react_app(request):
    return render(request, 'studio/insta_users_r.html', {})



