#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Amit Pal <amix.pal@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

try:
    import simplejson as json
except ImportError:
    import json

import datetime

from django.utils.translation import ugettext as _
import pytz
import datetime as dt
import time
from time import localtime
from datetime import timedelta

from netadmin.permissions.utils import filter_user_objects
from netadmin.networks.models import Host
from netadmin.shortcuts import get_host, get_timezone, timezone_to_UTC
from netadmin.events.models import Event, EventType



class EventParseError(Exception):
    pass

def filter_user_events(user):
    """Returns events accessible to specified user.
    """
    hosts = filter_user_objects(user, Host)
    pks = [host.pk for host in hosts]
    events_object = Event.objects.filter(source_host__pk__in=pks)
    return get_utc_time(user,events_object)
    
def get_event_data(request, event_dict):
    """
    Creates dictionary with parameters for Event's __init__ method. If needed
    function also creates host and event type and saves them. If function
    cannot find obligatory fields in event_dict, it raises EventParseError
    exception.
    """
    required_fields = ['timestamp', 'protocol', 'fields_class', 'event_type',
                       'description', 'short_description']
    base_fields = required_fields + ['is_report', 'hostname',
                                     'source_host_ipv6', 'source_host_ipv4']
    
    # make sure that event_dict contains all fields we need
    # (also make sure that these fields aren't empty)
    for field_name in required_fields:
        if field_name not in event_dict:
            raise EventParseError("Following field is not specified: %s" \
                                    % field_name)
        if not event_dict[field_name]:
            raise EventParseError("Following field must not be empty: %s" \
                                    % field_name)
        
    message = event_dict['description']
    short_message = event_dict['short_description']
    timestamp = event_dict['timestamp']
    protocol = event_dict['protocol']
    event_type_name = event_dict['event_type']
    fields_class = event_dict['fields_class']
    
    ipv4 = event_dict.get('source_host_ipv4')
    ipv6 = event_dict.get('source_host_ipv6')
    hostname = event_dict.get('hostname')
    
    try:
        if hostname:
            source_host = Host.objects.get(name=hostname, user=request.user)
        else:
            if ipv4 and ipv6:
                source_host = Host.objects.get(ipv4=ipv4, ipv6=ipv6,
                                               user=request.user)
            elif ipv4:
                source_host = Host.objects.get(ipv4=ipv4, user=request.user)
            elif ipv6:
                source_host = Host.objects.get(ipv6=ipv6, user=request.user)
            else:
                source_host = None
    except Host.DoesNotExist:
        source_host = Host(name=hostname, ipv4=ipv4, ipv6=ipv6,
                           user=request.user)
        source_host.save()
    
    try:
        event_type = EventType.objects.get(name=event_type_name,
                                           user=request.user)
    except EventType.DoesNotExist:
        event_type = EventType(name=event_type_name, user=request.user)
        event_type.save()
        
    fields_data_dict = {}
    for field in event_dict:
        if field not in base_fields:
            fields_data_dict[field] = event_dict[field]
    fields_data = json.dumps(fields_data_dict)
        
    event_data = {
        'message': message,
        'short_message': short_message,
        'timestamp': datetime.datetime.fromtimestamp(float(timestamp)),
        'protocol': protocol,
        'fields_class': fields_class,
        'fields_data': fields_data,
        'source_host': source_host,
        'event_type': event_type
    }
    
    return event_data
    
def get_utc_time(user, event_obj):
    for i in range(0,len(event_obj)):
        host = get_host(id = event_obj[i].source_host_id)
        host_timezone = host.timezone
        host_utc = pytz.timezone(host_timezone) 
        
        """To convert unicode to pytz datetime"""
        user_timezone = get_timezone(user=user)
        user_utc = pytz.timezone(user_timezone) 
        
        """To convert unicode to pytz datetime"""
        local_time = event_obj[i].timestamp
        localized_datetime_host = host_utc.localize(local_time)
        localized_datetime_user = user_utc.localize(local_time)
        differ_datetime_event = localized_datetime_host - localized_datetime_user
        local_time_new = local_time - differ_datetime_event
        return Event.objects.filter(source_host__pk__in=pks)
        
        
        
        
        
        
        
    

@@ -937,104 +937,12 @@
 ort 
-pytz%0Aimport datetime as dt%0Aimport time%0Afrom time import localtime%0Afrom datetime import timedelta
+time
 %0A%0Afr
@@ -1044,79 +1044,8 @@
 ost%0A
-from netadmin.shortcuts import get_host, get_timezone, timezone_to_UTC%0A
 from
@@ -1093,18 +1093,16 @@
 ntType%0A%0A
-%0A%0A
 class Ev
@@ -4466,885 +4466,4 @@
 ata%0A
-    %0Adef get_utc_time(user, event_obj):%0A    for i in range(0,len(event_obj)):%0A        host = get_host(id = event_obj%5Bi%5D.source_host_id)%0A        host_timezone = host.timezone%0A        host_utc = pytz.timezone(host_timezone) %0A        %0A        %22%22%22To convert unicode to pytz datetime%22%22%22%0A        user_timezone = get_timezone(user=user)%0A        user_utc = pytz.timezone(user_timezone) %0A        %0A        %22%22%22To convert unicode to pytz datetime%22%22%22%0A        local_time = event_obj%5Bi%5D.timestamp%0A        localized_datetime_host = host_utc.localize(local_time)%0A        localized_datetime_user = user_utc.localize(local_time)%0A        differ_datetime_event = localized_datetime_host - localized_datetime_user%0A        local_time_new = local_time - differ_datetime_event%0A        return Event.objects.filter(source_host__pk__in=pks)%0A        %0A        %0A        %0A        %0A        %0A        %0A        %0A    %0A

Remove import timezone_to_utc