#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter load
    author:rabin
"""
from demeter.web import *

class Load(Base):
	KEYS = ('admin', 'farm')

	def setting(self):
		self.search()
		self.admin()

	def admin(self):
		admin = 1
		self.data['auth'] = True
		
		if 'admin' in self.data['setting'] and self.data['setting']['admin'] > 0:
			self.data['setting']['adminInfo'] = self.service('common').one('manage_admin', id=self.data['setting']['admin'])
			if self.data['setting']['adminInfo']:
				self.data['setting']['roleInfo'] = self.service('common').one('manage_role', id=self.data['setting']['adminInfo']['role_id'])
		else:
			#self.redirect('/user/login')
			return

		if 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
			self.data['setting']['farmInfo'] = self.service('common').one('farm', id=self.data['setting']['farm'])

		self.data['setting']['menuList'] = self.menu()

		if self.data['setting']['adminInfo']['id'] == admin:
			if 'menu' in self.data['setting']:
				del self.data['setting']['menu']
		else:
			self.data['setting']['menu'] = ['_/', '_/login', '_/main', '_/admin/log_update']
			menu = self.data['setting']['roleInfo']['auth'] + ','
			for i,j in enumerate(self.data['setting']['menuList'][1]):
				m = 0
				for n in j[0]:
					if n+',' in menu:
						l = str(i)+'_'+str(n)
						self.data['setting']['menu'].append(l)
						self.data['setting']['menu'].append(l + '_update')
					m = m + 1
			self.data['setting']['menu'] = ',' + ",".join(self.data['setting']['menu'])+','

			uri = '_' + self.request.uri + ','
			if self.data['setting']['admin'] != admin and uri not in self.data['setting']['menu']:
				self.data['auth'] = False
		self.data['setting']['web'] = Demeter.config['web']['url']
		self.data['setting']['farmList'] = self.service('common').list('farm')

	def menu(self):
		parent = [['农场与设备管理', '网站管理', '基础设置'],['&#xe62e;', '&#xe62a;', '&#xe614;']]
		child = [
			[['/farm/farm','/farm/product','/device/gateway','/device/info','/device/info?search_status-hidden-=1','/work/work','/work/category','/work/method','/work/land','/origin/batch','/farm/user','/device/printer','/msg/msg'],['农场列表', '农场产品管理', '网关管理', '设备管理', '离线设备列表', '农场农事管理', '农场农事分类', '农场劳作方式', '农场地块管理', '溯源批次管理','农场用户管理','打印机管理', '消息提醒']]
			,[['/web/set','/web/help_category','/web/help','/web/category','/web/article','/web/menu'],['网站资料设置', '帮助分类', '发布帮助内容', '文章分类', '发布内容文章', '菜单管理']]
			,[['/device/type','/hardware/type','/device/notice_type','/msg/type','/admin/admin','/admin/role','/hardware/hardware', '/admin/log'],['设备类型管理','硬件类型管理', '设备错误码设置', '消息类型设置', '管理员设置', '管理权限设置','硬件设备记录', '系统日志']]
			]
		return (parent,child)
