# Path: ISeeNN/annotator/models.py
# class AnnoQuery(Document):
#     query_image_id = fields.ObjectIdField()
#     target_image_ids = fields.ListField(fields.ObjectIdField())
#     meta = {
#         'indexes': [
#             {
#                 'fields': ['query_image_id'],
#                 'unique': True
#             }
#         ]
#     }
# 
#     def __str__(self):
#         return str(self.id)
# 
# class AnnoUser(Document):
#     user_name = fields.StringField(required=True)
#     __password = fields.StringField(required=True)
#     annotation_list = fields.ListField(fields.ReferenceField(AnnoQuery))
#     label_index = fields.IntField(default=-1)
#     meta = {
#         'indexes': ['#user_name']
#     }
# 
#     def set_password(self, password):
#         encrypt = PasswordEncryption()
#         self.__password = encrypt.get_password(password)
# 
#     def validate_password(self, password):
#         encrypt = PasswordEncryption()
#         return encrypt.validate(password, self.__password)
# 
#     def clean(self):
#         if self.label_index == -1:
#             queries = AnnoQuery.objects.all()
#             perm = np.random.permutation(len(queries))
#             number = len(queries)
#             self.annotation_list = []
#             perm_list = perm[:number].tolist()
#             for id in range(number):
#                 self.annotation_list.append(queries[perm_list[id]])
#             self.label_index = 0
# 
#     @property
#     def current_annotation_id(self):
#         return self.annotation_list[self.label_index].id
# 
#     @property
#     def current_query_id(self):
#         return self.annotation_list[self.label_index].query_image_id
# 
#     @property
#     def current_annotation(self):
#         return self.annotation_list[self.label_index].target_image_ids
# 
#     @property
#     def completed(self):
#         return self.label_index >= len(self.annotation_list)
# 
# class AnnoAnnotation(Document):
#     user = fields.ObjectIdField()
#     query = fields.ObjectIdField()
#     scores = fields.ListField(fields.FloatField())
#     date = fields.DateTimeField(default=datetime.datetime.now)
#     meta = {
#         'indexes': ['#user','#query']
#     }
# 
# Path: ISeeNN/annotator/models.py
# class LoginForm(forms.Form):
#     user_name = forms.CharField(label='User Name', min_length=3)
#     password = forms.CharField(widget=forms.PasswordInput(), label='Password', min_length=3)
# 
# class RegisterForm(forms.Form):
#     user_name = forms.CharField(label='User Name')
#     password = forms.CharField(widget=forms.PasswordInput(), label='Password', min_length=3)
#     password_cfm = forms.CharField(widget=forms.PasswordInput(), label='Repeat Password', min_length=3)
# 
# class AnnotateForm(forms.Form):
#     query_id = forms.CharField(min_length=24, max_length=24)
#     scores = forms.CharField()


from django.shortcuts import render, reverse
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound
from bson import ObjectId
from search_web.models import Feature
from search_web.views import get_results, get_index_id, get_index_count, get_image_meta
from .models import AnnoQuery, AnnoUser, AnnoAnnotation
from .models import LoginForm, RegisterForm, AnnotateForm
import random
import numpy as np
import json
@authorize_admin
def confirm_select(request, image_id):
    feature = Feature.objects.get(identity=settings.FEATURE_IDENTITY, image=image_id)
    query_feat = np.frombuffer(feature.data, dtype='float32')
    results = get_results(query_feat)
    result_list = [ObjectId(x.id) for x in results]
    result_list = np.random.permutation(result_list).tolist()
    anno_query = AnnoQuery(query_image_id = ObjectId(image_id), target_image_ids = result_list)
    anno_query.save()
    return HttpResponseRedirect(reverse('annotator:select'))

@authorize_user
@authorize_admin
def view_selected(request):
    anno_queries = AnnoQuery.objects.all().only('query_image_id')
    results = []
    for query in anno_queries:
        (width, height) = get_image_meta(query.query_image_id)
        results.append({'query_image_id': query.query_image_id,
                        'width': width,
                        'height': height})
    return render(request, 'annotator/view_select.html', {
        'queries': results
    })


@authorize_user
@authorize_admin
def view_selected_detail(request, query_id):
    try:

# Path: ISeeNN/annotator/models.py
# class AnnoQuery(Document):
#     query_image_id = fields.ObjectIdField()
#     target_image_ids = fields.ListField(fields.ObjectIdField())
#     meta = {
#         'indexes': [
#             {
#                 'fields': ['query_image_id'],
#                 'unique': True
#             }
#         ]
#     }
# 
#     def __str__(self):
#         return str(self.id)
# 
# class AnnoUser(Document):
#     user_name = fields.StringField(required=True)
#     __password = fields.StringField(required=True)
#     annotation_list = fields.ListField(fields.ReferenceField(AnnoQuery))
#     label_index = fields.IntField(default=-1)
#     meta = {
#         'indexes': ['#user_name']
#     }
# 
#     def set_password(self, password):
#         encrypt = PasswordEncryption()
#         self.__password = encrypt.get_password(password)
# 
#     def validate_password(self, password):
#         encrypt = PasswordEncryption()
#         return encrypt.validate(password, self.__password)
# 
#     def clean(self):
#         if self.label_index == -1:
#             queries = AnnoQuery.objects.all()
#             perm = np.random.permutation(len(queries))
#             number = len(queries)
#             self.annotation_list = []
#             perm_list = perm[:number].tolist()
#             for id in range(number):
#                 self.annotation_list.append(queries[perm_list[id]])
#             self.label_index = 0
# 
#     @property
#     def current_annotation_id(self):
#         return self.annotation_list[self.label_index].id
# 
#     @property
#     def current_query_id(self):
#         return self.annotation_list[self.label_index].query_image_id
# 
#     @property
#     def current_annotation(self):
#         return self.annotation_list[self.label_index].target_image_ids
# 
#     @property
#     def completed(self):
#         return self.label_index >= len(self.annotation_list)
# 
# class AnnoAnnotation(Document):
#     user = fields.ObjectIdField()
#     query = fields.ObjectIdField()
#     scores = fields.ListField(fields.FloatField())
#     date = fields.DateTimeField(default=datetime.datetime.now)
#     meta = {
#         'indexes': ['#user','#query']
#     }
# 
# Path: ISeeNN/annotator/models.py
# class LoginForm(forms.Form):
#     user_name = forms.CharField(label='User Name', min_length=3)
#     password = forms.CharField(widget=forms.PasswordInput(), label='Password', min_length=3)
# 
# class RegisterForm(forms.Form):
#     user_name = forms.CharField(label='User Name')
#     password = forms.CharField(widget=forms.PasswordInput(), label='Password', min_length=3)
#     password_cfm = forms.CharField(widget=forms.PasswordInput(), label='Repeat Password', min_length=3)
# 
# class AnnotateForm(forms.Form):
#     query_id = forms.CharField(min_length=24, max_length=24)
#     scores = forms.CharField()


# Path: ISeeNN/annotator/views.py
from django.shortcuts import render, reverse
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound
from bson import ObjectId
from search_web.models import Feature
from search_web.views import get_results, get_index_id, get_index_count, get_image_meta
from .models import AnnoQuery, AnnoUser, AnnoAnnotation
from .models import LoginForm, RegisterForm, AnnotateForm
import random
import numpy as np
import json

@authorize_admin
def confirm_select(request, image_id):
    feature = Feature.objects.get(identity=settings.FEATURE_IDENTITY, image=image_id)
    query_feat = np.frombuffer(feature.data, dtype='float32')
    results = get_results(query_feat)
    result_list = [ObjectId(x.id) for x in results]
    result_list = np.random.permutation(result_list).tolist()
    anno_query = AnnoQuery(query_image_id = ObjectId(image_id), target_image_ids = result_list)
    anno_query.save()
    return HttpResponseRedirect(reverse('annotator:select'))

@authorize_user
@authorize_admin
def view_selected(request):
    anno_queries = AnnoQuery.objects.all().only('query_image_id')
    results = []
    for query in anno_queries:
        (width, height) = get_image_meta(query.query_image_id)
        results.append({'query_image_id': query.query_image_id,
                        'width': width,
                        'height': height})
    return render(request, 'annotator/view_select.html', {
        'queries': results
    })


@authorize_user
@authorize_admin
def view_selected_detail(request, query_id):
    try:

        anno_query = AnnoQuery.objects.get(query_image_id=query_id)