__author__ = 'vince'
__contact__ = 'thssvince@163.com'
__date__ = '2014-12-05'

from PIL import Image
import imagehash
import numpy as np
import os
import time
import copy
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from image import  REL_IMG_DIR, image, get_image_by_paths
from utils import text2word_list
import settings


IMG_DIR = settings.IMG_DIR
response_number = 10

COL_NUM = 5


def index(request):
    return render_to_response('index.html', {}, context_instance=RequestContext(request))


def handle_uploaded_file(f):
    path = IMG_DIR+str(int(time.time()))+'.'+f.name.split('.')[-1]
    with open(path, 'wb+') as info:
        for chunk in f.chunks():
            info.write(chunk)
    return path


def get_result(request):
    if request.method == 'POST':
        if request.FILES:
            img_name_list = copy.copy(settings.get_name_list())
            tree = copy.copy(settings.get_tree())
            filename = handle_uploaded_file(request.FILES['search-img'])
            hash3 = imagehash.dhash(Image.open(filename))
            os.remove(filename)
            list3 = settings.hash2list(hash3)
            if img_name_list.__len__() < response_number:
                img_index = tree.query(np.array(list3), img_name_list.__len__())
            else:
                img_index = tree.query(np.array(list3), response_number)

            img_list = list()
            for i in img_index[1]:
                path = unicode(REL_IMG_DIR + img_name_list[i])
                img_list.append(path)
            # get image info
            img_info = get_image_info_by_paths(img_list)
            return render_to_response('result.html', {"img_info": display_image_info(img_info), 'scale': 200,
                                                      }, context_instance=RequestContext(request))
        else:
            if request.POST['search-text']:
                img_info = handle_text_search(text2word_list(request.POST['search-text']))
                return render_to_response('result.html', { "img_info":img_info, "query": request.POST['search-text'], 'scale': 200,
                                                          }, context_instance=RequestContext(request))
            else:
                img_list = list()
                return render_to_response('result.html', {"img_list": img_list,
                                                          }, context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect("/")


def handle_text_search(texts):
    # build data set in memory
    img_list = list()
    data_set = dict()
    precise_path_list = list()
    fuzzy_path_list = list()
    tag_list = list()
    tag_collection =copy.copy(settings.get_tag_list())
    for tag in tag_collection:
        data_set[tag['name']] = tag['paths']
        tag_list.append(tag)
    # query
    for text in texts:
        if data_set.has_key(text):  # Precise query
            precise_path_list.append(data_set[text])
        else:                       # Fuzzy query
            for tag in tag_list:
                if text.find(tag['name']) >= 0:
                    fuzzy_path_list.append(data_set[tag['name']])
                else:
                    if tag['name'].find(text) >= 0:
                        fuzzy_path_list.append(data_set[tag['name']])
    # intersection
    if precise_path_list:
        img_list = precise_path_list[0]
        for path in precise_path_list:
            img_list = list(set(img_list).intersection(set(path)))
    # union
    if fuzzy_path_list:
        for path in fuzzy_path_list:
            img_list = list(set(img_list).union(set(path)))
    # compute similarity
    if img_list:
        img_info = get_image_info_by_paths(img_list)
        return display_image_info(img_info)
    else:
        return list()

'''
 get detailed image info by paths from database
 '''
def get_image_info_by_paths(img_list):
    images = get_image_by_paths(img_list) # get title and tags
    img_info = list()
    for img in images:
        img_info.append(image(img['path'], img['title'], img['url'], img['width'], img['height'], img['tags']))
    return img_info


'''
 display the image info(path, title, original url)
'''
def display_image_info(img_list):
    img_info = list()
    count = 0
    img = list()
    for imgl in img_list:
        img.append(imgl)
        count += 1
        if count % COL_NUM == 0:
            img_info.append(img)
            img = list()
    if count % COL_NUM:
        img_info.append(img)
    return img_info
