import os
from jinja2 import Environment, FileSystemLoader
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
template_loader = FileSystemLoader(searchpath=BASE_DIR + "/templates")
jinja = Environment(loader=template_loader)

from odoo import http
import logging

_logger = logging.getLogger(__name__)


class NoticeController(http.Controller):

    @http.route('/v1/page/notice/detail')
    def pc_notice_details(self, **kwargs):
        _id = int(kwargs.get('id') or 0)
        _type = kwargs.get('type', None)
        values = {
            'title': '',
            'content': '',
            'attachment': []
        }
        if _id:
            if _type == 'news':
                news = http.request.env['jd.news'].browse(_id)
                values.update({
                    'title': news.title,
                    'content': news.content
                })
            else:
                notice = http.request.env['jd.notice'].browse(_id)
                values.update({
                    'title': notice.title,
                    'content': notice.content
                })
                attr = []
                for at in notice.attachment_ids:
                    #http://127.0.0.1:8069/web/content?model=jd.notice.file&field=file&id=1&download=true&filename_field=name
                    attr.append({
                        'url': '/web/content?model=jd.notice.file&field=file&id=%d&download=true&filename_field=%s' % (at.id,at.name),
                        'name': at.name
                    })
                values.update({
                    'attachment': attr
                })
        template = jinja.get_template('notice_detail.html')
        return template.render(data=values)

    @http.route('/v1/page/notice/list', auth='public', csrf=False)
    def mobile_notice_list(self, **kwargs):
        template = jinja.get_template('notice_list.html')
        return template.render(data={})

    @http.route('/v1/page/notice/view', auth='public', csrf=False)
    def mobile_inspect_view(self, **kwargs):
        notice_id = [int(kwargs.get('notice_id', 0))]
        values = {}
        if notice_id > 0:
            notice = http.request.env['jd.notice'].browse(notice_id)
            if notice is not None:
                values = {
                    'title': notice.title,
                    'content': notice.content
                }

        template = jinja.get_template('notice_view.html')
        return template.render(data=values)
