# vim: set expandtab sw=4 ts=4:
'''
Interface to Keen IO.

Copyright (C) 2014 Dieter Adriaenssens <ruleant@users.sourceforge.net>

This file is part of buildtime-trend
<https://github.com/ruleant/buildtime-trend/>

This program 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
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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''

import os
import keen
from keen import scoped_keys
from buildtimetrend.tools import add_project_info_dict
from buildtimetrend.tools import add_project_info_list
from buildtimetrend.tools import check_file


def keen_io_writable():
    '''
    Check if login keys for Keen IO API are set, to allow writing.
    '''
    if "KEEN_PROJECT_ID" in os.environ and "KEEN_WRITE_KEY" in os.environ:
        return True
    return False


def keen_io_readable():
    '''
    Check if login keys for Keen IO API are set, to allow reading.
    '''
    if "KEEN_PROJECT_ID" in os.environ and "KEEN_READ_KEY" in os.environ:
        return True
    return False


def keen_io_generate_read_key(repo):
    '''
    Create scoped key for reading only the build-stages related data.
    Param repo : github repository slug (fe. ruleant/buildtime-trend)
    '''
    if "KEEN_MASTER_KEY" in os.environ:
        master_key = os.getenv("KEEN_MASTER_KEY")
        privileges = {
            "filters": [{
                "property_name": "build.repo",
                "operator": "eq",
                "property_value": repo
            }],
            "allowed_operations": ["read"]
        }

        return scoped_keys.encrypt(master_key, privileges)
    return None


def keen_add_event(event_collection, payload):
    '''
    Wrapper for keen.add_event(), adds project info
    Param event_collection : collection event data is submitted to
    Param payload : data that is submitted
    '''
    # add project info to this event
    payload = add_project_info_dict(payload)

    # submit list of events to Keen.io
    keen.add_event(event_collection, payload)


def keen_add_events(event_collection, payload):
    '''
    Wrapper for keen.add_events(), adds project info to each event
    Param event_collection : collection event data is submitted to
    Param payload : array of events that is submitted
    '''
    # add project info to each event
    payload = add_project_info_list(payload)

    # submit list of events to Keen.io
    keen.add_events({event_collection: payload})


def generate_overview_config_file(repo):
    '''
    Generates a config file for the overview HTML file that contains the
    graphs generated by Keen.io
    '''
    if "BUILD_TREND_SAMPLE_CONFIGFILE" in os.environ \
            and "BUILD_TREND_CONFIGFILE" in os.environ \
            and "KEEN_PROJECT_ID" in os.environ:
        sample_filename = os.getenv("BUILD_TREND_SAMPLE_CONFIGFILE")
        config_file = os.getenv("BUILD_TREND_CONFIGFILE")
        keen_project_id = os.getenv("KEEN_PROJECT_ID")
        read_key = keen_io_generate_read_key(repo)

        # check if sample config file exists
        if not check_file(sample_filename):
            return

        # list of string pairs to be replaced (search string : new string)
        replacements = {
            'keen_project_id': str(keen_project_id),
            'keen_read_key': str(read_key),
            'project_name': str(repo)
        }

        with open(sample_filename, 'rb') as infile, \
                open(config_file, 'w') as outfile:
            for line in infile:
                for src, target in replacements.iteritems():
                    line = line.replace(src, target)
                outfile.write(line)

        print "Created trends overview config file"
    else:
        print "Trends overview config file was not created"

@@ -3042,16 +3042,21 @@
 %0A    if 
+not (
 %22BUILD_T
@@ -3084,34 +3084,32 @@
 E%22 in os.environ
- %5C
 %0A            and
@@ -3147,18 +3147,16 @@
 .environ
- %5C
 %0A       
@@ -3191,30 +3191,88 @@
 n os.environ
+)
 :%0A    
+    print %22Trends overview config file was not created%22%0A%0A
     sample_f
@@ -3320,28 +3320,24 @@
 ONFIGFILE%22)%0A
-    
     config_f
@@ -3378,20 +3378,16 @@
 GFILE%22)%0A
-    
     keen
@@ -3433,64 +3433,9 @@
 D%22)%0A
-        read_key = keen_io_generate_read_key(repo)%0A%0A    
+%0A
     
@@ -3475,20 +3475,16 @@
 sts%0A    
-  
-  
 if not c
@@ -3515,28 +3515,24 @@
 e):%0A        
-    
 return%0A%0A    
@@ -3527,24 +3527,92 @@
 return%0A%0A    
+# generate read key%0A    read_key = keen_io_generate_read_key(repo)%0A%0A
     # list o
@@ -3670,20 +3670,16 @@
 string)%0A
-    
     repl
@@ -3695,28 +3695,24 @@
 = %7B%0A        
-   
- 
 'keen_projec
@@ -3740,20 +3740,16 @@
 ct_id),%0A
-    
         
@@ -3788,20 +3788,16 @@
         
-    
 'project
@@ -3814,35 +3814,27 @@
 r(repo)%0A    
- 
-   %7D%0A%0A    
+%7D%0A%0A
     with ope
@@ -3883,20 +3883,16 @@
         
-   
- 
 open(con
@@ -3914,28 +3914,24 @@
 as outfile:%0A
-    
         for 
@@ -3954,28 +3954,24 @@
             
-    
 for src, tar
@@ -4019,20 +4019,16 @@
         
- 
-   
 line = l
@@ -4064,20 +4064,16 @@
         
-    
 outfile.
@@ -4085,20 +4085,16 @@
 (line)%0A%0A
-    
     prin
@@ -4137,74 +4137,4 @@
 le%22%0A
-    else:%0A        print %22Trends overview config file was not created%22%0A

refactor generate_overview_config_file