# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
from gluon.dal import Field
from rdflib.syntax.parsers.n3p.n3p import notNameChars
#from applications.login.models.cas import CAS
#from applications.login.models import cas
from gluon.contrib.login_methods.cas_auth import CasAuth

#########################################################################
## This scaffolding model makes your app work on Google App Engine too
#########################################################################
 
if request.env.web2py_runtime_gae:            # if running on Google App Engine
    db = DAL('google:datastore')              # connect to Google BigTable
                                              # optional DAL('gae://namespace')
    session.connect(request, response, db = db) # and store sessions and tickets there
    ### or use the following lines to store sessions in Memcache
    # from gluon.contrib.memdb import MEMDB
    # from google.appengine.api.memcache import Client
    # session.connect(request, response, db = MEMDB(Client()))
else:                                         # else use a normal relational database
    #db = DAL('sqlite://storage.sqlite')       # if not, use SQLite or other DB
    username = 'intranet'
    passwd = 'password'
    server = '192.168.2.30:3306' 
    database = 'intranet'
    db = DAL("mysql://%s:%s@%s/%s" % (username,passwd,server,database))
# by default give a view/generic.extension to all actions from localhost
# none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*'] if request.is_local else []

#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - crud actions
## (more options discussed in gluon/tools.py)
#########################################################################

from gluon.tools import Mail, Auth, Crud, Service, PluginManager, prettydate

mail = Mail()                                  # mailer
auth = Auth(db)     # authentication/authorization
crud = Crud(db)                                # for CRUD helpers using auth
service = Service()                            # for json, xml, jsonrpc, xmlrpc, amfrpc
plugins = PluginManager()                      # for configuring plugins

mail.settings.server =  'mail.citydeal.de:587'  # 'logging' or your SMTP server
mail.settings.sender = 'intranet@clubeurbano.com.br'         # your email
mail.settings.login = 'intranet:5sySu7SL'      # your credentials or None

auth.settings.hmac_key = 'sha512:5134f15a-c451-4973-b1cb-96b9b5cb4195'   # before define_tables()
auth.settings.cas_domains.append('http://172.16.7.10:8000/AgendamentoReunioes')
auth.settings.cas_domains.append('http://172.16.7.10:8000/ControleDeAtivos')
#auth.settings.cas_domains.append('http://172.16.3.90:55030/')
#auth.settings.cas_domains.append('http://172.16.3.90:55030/*')
#auth.settings.cas_domains.append('http://172.16.3.90/')
#auth.settings.cas_domains.append('http://172.16.3.90/*')
#auth.settings.cas_domains.append('http://172.16.3.90:55030/intranet')
#auth.settings.cas_domains.append('http://172.16.3.90:55030/BackOffice')
#auth.settings.cas_domains.append('http://172.16.3.90/intranet')
#auth.settings.cas_domains.append('http://172.16.3.90/BackOffice')
#auth.settings.login_form=CasAuth(urlbase = "https://172.16.7.10/login/default/user/cas",
 #                                    actions=['login','validate','logout'])

auth.settings.table_user_name = 'Usuario'

db.define_table(auth.settings.table_user_name,
                Field('id','integer'),
                Field('IdCargo', 'integer',notnull=True),
                Field('IdCentroCusto','integer',notnull=True),
                Field('IdItemCentroCusto','integer',notnull=True),
                Field('Nome',length=255,notnull=True),
                Field('Matricula','string',length=10,notnull=True),
                Field('email',length=255,default=''),#requires=IS_EMAIL()),
                #Field('Senha','string',length=32,notnull=True),
                Field('Ramal',length=10),
                Field('Skype',length=45),
                Field('Celular',length=20),
                Field('IdMunicipio','integer'),
                Field('Situacao','boolean'),
                Field('UltimoLogin','datetime'),
                #Field('first_name', length=128, default=''),
                #Field('last_name', length=128, default=''),
                #Field('email', length=128, default='', unique=True),
                Field('password', 'password', length=512, readable=False, label='Password'),
                Field('registration_key', length=512, writable=False, readable=False, default=''),
                Field('reset_password_key', length=512,writable=False, readable=False, default=''),
                Field('registration_id', length=512, writable=False, readable=False, default=''),
                Field('username','string'),
                migrate=False)
                #auth.settings.table_user_name
custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table
custom_auth_table.Nome.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)

custom_auth_table.password.requires = [IS_STRONG(), CRYPT()]
custom_auth_table.email.requires = [IS_EMAIL(error_message=auth.messages.invalid_email)]    #IS_NOT_IN_DB(db, custom_auth_table.email)]

auth.settings.table_user = custom_auth_table
auth.settings.actions_disabled.append('register')
auth.settings.login_next = 'http://www.google.com'
auth.settings.mailer = mail                    # for user email verification
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.messages.verify_email = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['verify_email'])+'/%(key)s to verify your email'
auth.settings.reset_password_requires_verification = True
auth.messages.reset_password = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['reset_password'])+'/%(key)s to reset your password'
auth.define_tables(username=True,migrate=False)                           # creates all needed tables

#########################################################################
## If you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc.
## register with janrain.com, uncomment and customize following
# from gluon.contrib.login_methods.rpx_account import RPXAccount
# auth.settings.actions_disabled = \
#    ['register','change_password','request_reset_password']
# auth.settings.login_form = RPXAccount(request, api_key='...',domain='...',
#    url = "http://localhost:8000/%s/default/user/login" % request.application)
## other login methods are in gluon/contrib/login_methods
#########################################################################

crud.settings.auth = None        # =auth to enforce authorization on crud

#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
##       'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
