#-------------------------------------------------------------------------------
# Copyright 2011 Ryan W Sims (rwsims@gmail.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------

import logging
import simplejson

from django import http
from django.views.generic import simple
from google.appengine.api import taskqueue
from google.appengine.ext import db

import forms
from vendors import models
from util import counters

def _count_orphans():
    q = models.Vendor.all()
    q.filter('category_count = ', 0)
    return q.count(1000)

def _count_empty_cats():
    q = models.VendorCategory.all()
    q.filter('vendor_count = ', 0)
    return q.count(100)

def index(request):
    vendor_count = counters.get_count('vendors')
    orphan_vendors = _count_orphans()
    category_count = counters.get_count('categories')
    empty_cats = _count_empty_cats()
    return simple.direct_to_template(request, 'sye_admin/index.html',
            {'category_count': category_count,
             'vendor_count': vendor_count,
             'orphan_vendors': orphan_vendors,
             'empty_cats': empty_cats,
             })

def all_valid(*forms):
    valid = True
    for form in forms:
        valid &= form.is_valid()
    return valid

def _link_map(data):
    maps = []
    for m in data:
        if len(m) == 0:
            continue
        d = {'title': m['title'],
             'url': m['url'],
             'class': models.LinkClasses[m['title']]}
        maps.append(d)
    return maps

def _update_category_txn(vendor, new, old):
    id = vendor.key().id()
    marker_key = db.Key.from_path('VendorMarker', id, parent = vendor.key())
    marker = db.get(marker_key)
    if not marker:
        marker = models.VendorMarker(key = marker_key)
    marker.sequence += 1
    db.put([vendor, marker])

    if len(new) > 0:
        taskqueue.Task(url = '/admin/tasks/update-cats',
                params = {
                    'vendor_id': id,
                    'categories': '|'.join(new),
                    'sequence': marker.sequence,
                    'present': True
                    }
                ).add(transactional = True)
    if len(old) > 0:
        taskqueue.Task(url = '/admin/tasks/update-cats',
                params = {
                    'vendor_id': id,
                    'categories': '|'.join(old),
                    'sequence': marker.sequence,
                    'present': False
                    }
                ).add(transactional = True)

def _update_vendor_categories(vendor, new_cats):
    if vendor.key() is None:
        raise TypeError, 'Must persist vendor before updating categories.'
    old_cats = vendor.categories
    vendor.set_categories(new_cats)
    db.run_in_transaction(_update_category_txn, vendor, new_cats, old_cats)

def _put_new_vendor(info, social_links, trackbacks, review_links, sye_reviews):
    vendor = models.Vendor(account_email = info['account_email'], name = info['name'])
    logging.info("Creating vendor " + vendor.name)
    # basic vendor info
    vendor.public_email = info['public_email']
    vendor.website = info['vendor_website']