# -*- coding: utf-8 -*-
__author__ = 'Alan Tai'
'''
Created on Jun 24, 2014

@author: Alan Tai
'''
import logging
import jinja2
import webapp2
import json

from dictionaries.dict_keys_values import KeysVaulesGeneral
from handlers.handler_webapp2_extra_auth import BaseHandler
from models.models_video_info import VideoInfo

# dictionaries
dict_general = KeysVaulesGeneral()

# jinja environment
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader('static/templates'))

# dispatchers
class VideosDataUploadDispatcher(BaseHandler):
    def post(self):
        """ handler of dealing with geo info update """
        if self._is_json(self.request.get('video_data')):
            json_article_data = json.loads(self.request.get('video_data'))
            for elem in json_article_data:
                query = VideoInfo.query(VideoInfo.id == elem["id"])
                if (query.count() == 0):
                    new_video = VideoInfo()
                    new_video.id = elem["id"]
                    new_video.sys_id = elem["sys_id"]
                    new_video.title = elem["title"]
                    new_video.description = elem["description"]
                    new_video.publishedAt = elem["publishedAt"]
                    new_video.thumbnails = elem["thumbnails"]
                    
                    new_video.put()
            status = 'success'
            
        else:
            status = 'received variable is not in JSON format'
        
        # ajax response
        ajax_response = {'status': status}
        self.response.out.headers['Content-Type'] = 'text/json'
        self.response.out.write(json.dumps(ajax_response))
        
    # check if variable is in json format
    def _is_json(self, arg_json):
        try:
            json.loads(arg_json)
        except ValueError:
            return False
        return True

# configuration
config = dict_general.config_setting

# app
app = webapp2.WSGIApplication([
    webapp2.Route(r'/videos/videos_info_handler', VideosDataUploadDispatcher, name='articles_info_handler')
], debug=True, config=config)

# log
logging.getLogger().setLevel(logging.DEBUG) 
from google.appengine.ext import ndb
    
