##############################################################################
# -*- coding: utf-8 -*-
# Project:     ControlIES
# Module:    MainLoop.py
# Purpose:     ControlIES web response
# Language:    Python 2.5
# Date:        7-Feb-2011.
# Ver:        7-Feb-2011.
# Author:    Manuel Mora Gordillo
# Copyright:    2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# ControlIES is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from twisted.web import server,resource,static
import twisted
import os
import simplejson as json
from Plugins.LdapConnection import LdapConnection, ILdapConnection
from Utils import LdapUtils

class ControlIESProtocol(resource.Resource):    

    isLeaf = True  # This is a resource end point.
    
    def __init__ (self):
        resource.Resource.__init__(self)        
        self.PageDir=""


    def render_GET(self, request):
        session = request.getSession()
        l = ILdapConnection(session)
        connection = l.connect()

        pagename=request.path[1:].lower()
            
        if  pagename=='':
            request.path='/index.html'
            pagename='index.html'
        
        if pagename=='main.html' and connection==False:
            request.path='/index.html'
            pagename='index.html'
            
        requestedfile = os.path.join(self.PageDir,request.path[1:])
        
        if not os.path.isfile(requestedfile):
            # Didn't find it? Return an error.
            request.setResponseCode(404)
            return"""
            <html><head><title>404 - No Such Resource</title></head>
            <body><h1>No Such Resource</h1>
            <p>File not found: %s - No such file.</p></body></html>
            """ % requestedfile

        # Look for the requested file.
        f=static.File(requestedfile)

        if f.type is None:
            f.type, f.encoding = static.getTypeAndEncoding(requestedfile,
                f.contentTypes,
                f.contentEncodings,
                f.defaultType)        
        
        if f.type:
            ctype=f.type.split(":")[0]
            # Send the headers.
            request.setHeader('content-type', ctype)
            
        if f.encoding:
            request.setHeader('content-encoding', f.encoding)
        # Send the page.               
        if twisted.version.major >= 9:
            static.NoRangeStaticProducer(request,f.openForReading()).start()
        else:
            static.FileTransfer(f.openForReading(), f.getFileSize(), request)
        return server.NOT_DONE_YET


    def render_POST(self, request):

        command = request.path[1:]

        session = request.getSession()
        l = ILdapConnection(session)
        print command

        if command == "authentication":
                    
            l.setCredentials(request.args['host'][0], request.args['user'][0], request.args['password'][0])
            response = l.process()
            return json.dumps({"connection" : response})
            
        if command == "users":
            from Plugins.Users import Users

            if request.args['action'][0] == "list":
                u = Users(l,"","","","","","","","","")
                response = u.list(request.args)
                return json.dumps(response)
                
            elif request.args['action'][0] == "searchUsername":
                u = Users(l,"",request.args['name'][0],request.args['surname'][0],"","","","","","")
                response = u.searchNewUsername()
                return json.dumps({"response" : response})
                
            elif request.args['action'][0] == "getUserData":
                u = Users(l,"","","","",request.args['user'][0],"","","","")
                response = u.getUserData()
                return json.dumps({"response" : response})

            elif request.args['action'][0] == "getAllUsers":
                response = LdapUtils.getAllUsers(l)
                return json.dumps(response)        

            elif request.args['action'][0] == "delete":
                u = Users(l,"","","","",request.args['user'][0],"","","","")
                response = u.delete()
                return json.dumps({"response" : response})
                
            else:
                departments=[]
                classrooms=[]                
                
                try:
                    departments = request.args['multiselect_departments']
                except:
                    pass

                try:
                    classrooms = request.args['multiselect_classrooms']
                except:
                    pass
                
                u = Users(l,request.args['type'][0],request.args['name'][0],request.args['surname'][0],request.args['nif'][0],request.args['user'][0],request.args['password'][0],request.args['password2'][0],departments,classrooms)
                response = u.process(request.args['action'][0])
                return json.dumps({"response" : response})

        # Gestion de Grupos
        if command == "groups":
            
            from Plugins.Groups import Groups 
            
            if request.args['action'][0] == "list":
                g = Groups(l,"","","")
                response = g.list(request.args)
                return json.dumps(response)
                
            elif request.args['action'][0] == "getAllGroups":
                response = LdapUtils.getAllGroups(l)
                return json.dumps(response)                

            elif request.args['action'][0] == "getGroupData":
                g = Groups(l,"",request.args['name'][0],"")
                response = g.getGroupData()
                return json.dumps({"response" : response})
                
            elif request.args['action'][0] == "delete":
                g = Groups(l,"",request.args['name'][0],"")
                response = g.delete()
                return json.dumps({"response" : response})
                
            else:
                g = Groups(l,request.args['type'][0], request.args['name'][0], request.args['users'][0])
                response = g.process(request.args['action'][0])
                return json.dumps({"response" : response})
                

        if command == "hosts":
            from Plugins.Hosts import Hosts

            if request.args['action'][0] == "list":
                h = Hosts (l,"","","","","")
                response = h.list(request.args)
                print "hosts-list"

                #prueba para encender un equipo
                #h = Hosts ("a21-pro","172.23.36.47","00:22:15:6e:9c:ba")
                #print "Encendiendo host "+h.getName()
                #h.wakeup()
                return json.dumps(response)
                
                
            elif request.args['action'][0] == "getThinclientGroups":
                h = Hosts (l,"","","","","")
                response = h.getThinclientGroups ()
                return json.dumps({"response" : response})    
                
            elif request.args['action'][0] == "getInternalGroups":
                h = Hosts (l,"","","","","")
                response = h.getInternalGroups ()
                return json.dumps({"response" : response})                        
                
                
            elif request.args['action'][0] == "getLTSPServers":
                h = Hosts (l,"","","","","")
                response = h.getLTSPServers ()
                return json.dumps({"response" : response})        


            elif request.args['action'][0] == "getLTSPStatus":
                f = open('/tmp/controlIES.ltpsSevers', 'r')
                computers = f.read().split(" ")
                computers.sort()
                
                f = open('/tmp/controlIES.ltpsTeachers', 'r')
                teachers = f.read().split(" ")
                teachers.sort()                

                return json.dumps({ "computers":computers, "teachers":teachers })


            elif request.args['action'][0] == "getClassroomDetails":

                import xmlrpclib
                from Plugins.Users import Users

                objUser = Users(l,"","","","",request.args['teacher'][0],"","","","")
                teacherData = objUser.getUserData()

                s = xmlrpclib.Server("http://" + request.args['classroom'][0] + ":8900");

                users = s.Users()

                response = []
                for u in users:
                    user = u.split("@")

                    objUser = Users(l,"","","","",user[0],"","","","")
                    photo = objUser.getUserPhoto()

                    response.append({ 'username': user[0], 'host': user[1], 'photo': photo })

                return json.dumps({ "teacher" : teacherData, "classroom" : request.args['classroom'][0], "students" : response })

            elif request.args['action'][0]=="delete":
                h = Hosts(l,request.args['cn'][0],"","",request.args['group'][0],request.args['type'][0])
                response = h.process(request.args['action'][0])
                return json.dumps({"response" : response})
                
            elif request.args['action'][0] == "getHostData":
                h = Hosts(l,request.args['cn'][0],"","",request.args['group'][0],request.args['type'][0])
                response = h.getHostData()
                return json.dumps({"response" : response})                
                
            else: #add, modify
                if request.args ['type'][0] == 'thinclient':
                    ip = ""
                else:
                    ip = request.args ['ip'][0]
                h = Hosts(l,request.args['name'][0],ip,request.args['mac'][0],request.args['group'][0],request.args['type'][0])
                response = h.process(request.args['action'][0])
                return json.dumps({"response" : response})
                
        if command == "dhcp":
            from Plugins.DHCP import DHCP
            from Plugins.LdapConnection import LdapConnection
            if request.args['action'][0] == "list":
                
                #busqueda dhcp
                search = l.search("cn=INTERNAL,cn=DHCP Config,dc=instituto,dc=extremadura,dc=es","dhcpOption=*",["dhcpOption"])                
                #obtengo valores de dhcpOPtion
                #OJO: Hacer algo para que no haya desbordamiento de indices
                dhcpOption = search[0][0][1]['dhcpOption']
                subnet_mask = dhcpOption[0].replace('subnet-mask ','')
                broadcast_address = dhcpOption[1].replace('broadcast-address ','')
                routers = dhcpOption[2].replace('routers ','')
                domain_name_servers = dhcpOption[3].replace('domain-name-servers ','')
                domain_name = dhcpOption[4].replace('domain-name ','')
                ntp_servers = dhcpOption[5].replace('ntp-servers ','')
                log_servers = dhcpOption[6].replace('log-servers ','')
                netbios_name_servers = dhcpOption[7].replace('netbios-name-servers ','')
                netbios_node_type = dhcpOption[8].replace('netbios-node-type ','')
                
                d = DHCP (self,subnet_mask,broadcast_address,routers,domain_name,ntp_servers,log_servers,netbios_name_servers,netbios_node_type)
                
                print "Mascara de red: " + d.subnet_mask
                print "Direccion de Broadcast: " + d.broadcast_address
                #return json.dumps(response)
            else:
                h = Hosts(l,request.args['name'][0],request.args['ip'][0],request.args['mac'][0])
                print request.args['name'][0]
                response = h.process(request.args['action'][0])
                return json.dumps({"response" : response})

        if command == "logout":
            request.getSession().expire()
            return json.dumps({"response" : "logout"})
            
        return

    def response_fail(self, messages=None):
        messages = messages or []
        return json.dumps({
            'status': 'fail',
            'errors': messages,
            'time': int(time())
        })        
    def response_ok(self, **kwds):
        kwds.update({'status': 'ok', 'time': int(time())})
        return json.dumps(kwds)    
