import csv
import os
import ParadoxConvert

__author__ = 'peter'


class SaveModels:
    def __init__(self, mod_path, resource_manager):
        self.province_path = os.path.join(mod_path[:-4], 'history', 'provinces')
        self.province_names = {}
        with open(os.path.join(mod_path[:-4], 'map', 'definition.csv'), 'rb') as resource:
            resource.readline()
            for line in csv.reader(resource, delimiter=';'):
                self.province_names[int(line[0])] = line[4]
        self.resource_manager = resource_manager
    def save(self, provinces):
        for file in os.listdir(self.province_path):
            os.remove(os.path.join(self.province_path, file))
        for province_id in provinces:
            new_model = []
            new_model = self.__set_if_exists(provinces[province_id], 'owner', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'controller', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'base_tax', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'manpower', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'capital', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'hre', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'is_city', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'religion', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'trade_goods', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'native_size', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'native_hostileness', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'native_ferocity', new_model)
            new_model = self.__set_if_exists(provinces[province_id], 'culture', new_model)
            new_model = self.__set_multiple_if_exists(provinces[province_id], 'discovered_by', new_model)
            new_model = self.__set_multiple_if_exists(provinces[province_id], 'add_core', new_model)
            for building in provinces[province_id].buildings:
                new_model = self.__set_if_exists(provinces[province_id], building, new_model)
            new_model == self.__calculate_history(provinces[province_id], new_model)
            modfile_name = os.path.join(self.province_path, str(province_id) + '-' + self.province_names[province_id] + '.txt')
            with open(os.path.join(self.province_path, modfile_name), 'w+b') as output:
                output.write(ParadoxConvert.serialize_object_to_eu4_file(new_model))
        pass
    def __set_if_exists(self, province, model_property, new_model):
        if hasattr(province, model_property):
            if getattr(province,model_property)['modified']:
                if len([property for property in new_model if property.keys()[0] == model_property]) > 0:
                    new_model = filter(new_model, lambda x: x.keys()[0] != model_property)
                new_model.append({model_property: "yes" if getattr(province,model_property)['value'] == True else getattr(province,model_property)['value'] })
        return new_model
    def __set_multiple_if_exists(self, province, model_property, new_model):
        if hasattr(province, model_property):
            for value in getattr(province, model_property):
                if value['modified']:
                    if len([property for property in new_model if (property.keys()[0] == model_property and property.values()[0] == "yes" if value == True else "no")]) == 0:
                        new_model.append({model_property: "yes" if value['value'] == True else value['value'] })
        return new_model
    def __calculate_history(self, province, new_model):
        for date in province.historical_events:
            historical_events = []
            for event in province.historical_events[date]:
                for effect in event['value']:
                    historical_events.append(effect);
            historical_date = {date: historical_events}
            new_model.append(historical_date)
        return new_model
    '''
        'buildings': buildings.populate,
        'history': history.populate
            '''