
import os
import unicodecsv

from iatidq import app

YEAR_MAP_FILE = '2012_2013_organisation_mapping.csv'
OLD_YEAR = '2012'
NEW_YEAR = '2013'
OLD_FIELD_ID = OLD_YEAR + '_id'
NEW_FIELD_ID = NEW_YEAR + '_id'
OLD_INDICATORS_FILE = OLD_YEAR + '_indicators.csv'
OLD_RESULTS_FILE = OLD_YEAR + '_results.csv'
NEW_INDICATOR_NAME = NEW_YEAR + '_indicator_name'

def get_old_organisation_id(organisation_code='GB-1'):
    path = app.config["DATA_STORAGE_DIR"]
    old_organisation_file = os.path.join(path, YEAR_MAP_FILE)

    old_organisation_data = unicodecsv.DictReader(file(old_organisation_file))
    for row in old_organisation_data:
        if row[NEW_FIELD_ID] == organisation_code:
            return row[OLD_FIELD_ID]

def get_old_indicators():
    path = app.config["DATA_STORAGE_DIR"]
    old_indicators_file = os.path.join(path, OLD_INDICATORS_FILE)
    old_indicators_data = unicodecsv.DictReader(file(old_indicators_file))

    indicator_data = {}
    for row in old_indicators_data:
        if ((row["question_number"]) and (row[NEW_INDICATOR_NAME])):
            indicator_data[int(row["question_number"])] = row[NEW_INDICATOR_NAME]
    return indicator_data

# read in(!) a CSV file of last year's results; it must have fields

# id              - not used
# question_id     - the indicator id of the question in the old data
# target_id       - the organisation ID in the old data
# result          - used in templates
# result_evidence - used in templates
# result_comments - used in templates
# result_review   - not used

    
def get_organisation_results(organisation_code, newindicators):
    old_organisation_id = get_old_organisation_id(organisation_code)
    old_indicators = get_old_indicators()

    path = app.config["DATA_STORAGE_DIR"]

    old_results_file = os.path.join(path, OLD_RESULTS_FILE)
    old_results_data = unicodecsv.DictReader(file(old_results_file))

    data = {}

    # old_indicators is a map from int -> string, e.g., 1 -> "foia"

    for d in old_results_data:
        if d["target_id"] == old_organisation_id:
            assert "question_id" in d
            question_id = int(d["question_id"])
            if question_id in old_indicators:
                data[old_indicators[question_id]] = d

    for indicator_name in newindicators:
        if indicator_name not in data:
            data[indicator_name] = { 'result': '' }

    return data

@@ -995,12 +995,29 @@
     
-if (
+question_number = int
 (row
@@ -1040,38 +1040,149 @@
 r%22%5D)
- and (row%5BNEW_INDICATOR_NAME%5D)
+%0A        new_indicator_name = row%5BNEW_INDICATOR_NAME%5D%0A%0A        assert question_number != 0%0A        if (question_number and new_indicator_name
 ):%0A 
@@ -1207,25 +1207,16 @@
 or_data%5B
-int(row%5B%22
 question
@@ -1226,38 +1226,31 @@
 mber
-%22%5D)
 %5D = 
-row%5BNEW_INDICATOR_NAME%5D
+new_indicator_name%0A
 %0A   

make indicator mapping function more legible