#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import odoo
import jinja2
import sys
import os
import math
import random
import functools
from odoo import http
from odoo.http import content_disposition, dispatch_rpc, request, \
                      serialize_exception as _serialize_exception
from jinja2 import Environment, FileSystemLoader
from odoo.modules import get_resource_path
from cStringIO import StringIO
import imghdr

_logger = logging.getLogger(__name__)


class CommonService(http.Controller):
    @http.route('/web/common/random_culture/<int:num>', type='json', auth="none", csrf=False)
    def random_culture(self, num=1):
        """
        随机企业文化宣传语句json接口，用于长时间加载等待或错误提示页面
        :return:
        """
        lines = request.env['jd.init.culture'].get_random_line(num)
        if not lines:
            lines = [{'id': 0, 'line': u'...加载中...'}]
        return lines


class Binary(odoo.addons.web.controllers.main.Binary):
    @http.route([
        '/web/binary/company_logo',
        '/logo',
        '/logo.png',
    ], type='http', auth="none", cors="*")
    def company_logo(self, dbname=None, **kw):
        imgname = 'logo'
        imgext = '.png'
        placeholder = functools.partial(get_resource_path, 'jd_init', 'static', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    company = int(kw['company']) if kw and kw.get('company') else False
                    if company:
                        cr.execute("""SELECT logo_web, write_date
                                            FROM res_company
                                           WHERE id = %s
                                       """, (company,))
                    else:
                        cr.execute("""SELECT c.logo_web, c.write_date
                                            FROM res_users u
                                       LEFT JOIN res_company c
                                              ON c.id = u.company_id
                                           WHERE u.id = %s
                                       """, (uid,))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_base64 = str(row[0]).decode('base64')
                        image_data = StringIO(image_base64)
                        imgext = '.' + (imghdr.what(None, h=image_base64) or 'png')
                        response = http.send_file(image_data, filename=imgname + imgext, mtime=row[1])
                    else:
                        response = http.send_file(placeholder('nologo.png'))
            except Exception:
                response = http.send_file(placeholder(imgname + imgext))

        return response