# -*- coding: utf-8 -*-
import os

from ppms import ppms
from ppms.constants import *
from ppms.migration import ChangeDTPPacket, SQLPacket, PacketCategory, MaxVersionDependency, VersionType


DATAFIELD_DICTIONARY = {
                    ('000469', 32458): {'position': [29, 30]},
                    ('000469', 32457): {'position': [28, 29]},
                    ('000469', 98145): {'position': [27, 28]},
                    ('000469', 97074): {'position': [26, 27]},
                    ('000469', 50348): {'position': [25, 26]},
                    ('000469', 60758): {'position': [24, 25]},
                    }

NEW_DFS = {
    "generated": {
        "di": "060099",
        "da": "000469",
        "df_fieldnumber": 734187,
        "position": 24,
        "created_on": "04.04.12",
        "modified_on": "10.05.12",
        "rwdu": 7,
        "created_by": "PADU",
        "modified_by": "JB",
        "own_lic": "011",
        "opc": None,
        "owner": 7,
        "group": 7,
        "any": 7,
        "window": 1,
        "behavior": "i2",
        "default_value": "@Y"
                }
        }

MIGRATION_EXISTING_SCHEMAS = {
                    ("K000",): {"generated": [None, False]},
                    ("Q1B",): {"generated": [None, True]},
                    ("Q1V",): {"generated": [None, False]},
                    ("Q2B",): {"generated": [None, True]},
                    ("Q2V",): {"generated": [None, False]},
                    ("Q3B",): {"generated": [None, True]},
                    ("Q4B",): {"generated": [None, True]},
                    ("Q5B",): {"generated": [None, True]},
                    ("Q5VO",): {"generated": [None, False]},
                    ("Q6B",): {"generated": [None, True]},
                    ("Q7B",): {"generated": [None, False]}
                    }
        
SQL = {
    'port_itexts_of_di060099': 'wi12884_port_itext_di060099_generated.sql'
        }
        
class SchemaExportCustomerTables(SQLPacket, ChangeDTPPacket):
    '''Adds not ported itexts of DI060099 (Generated)
    Changes CU of MOD000230 (adds DI060099 (Generated) to DA000469)
    Migrates values of Venus to VenusOnEarth
    '''
    
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12884
    
    def get_dependencies(self):
        return (MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),)
            
    def create_generated_record(self, df_dictionary):
        succeed = 0
        for datafield in df_dictionary.keys():
            da_dict = df_dictionary.get(datafield)
            current_datafield_record = self.get_record(
                411, [da_dict.get("da"), da_dict.get("df_fieldnumber")], [213, 223])
            if current_datafield_record is None:
                current_datafield_record = ppms.create_record(411, da_dict)
                if current_datafield_record is not None:
                    if current_datafield_record.save():
                        succeed += 1
            else:
                if current_datafield_record.di.get_value() != da_dict.get("di"):
                    self.log(
                        "FAILED: There is already an other datafield with id '{df_id}' in dataarea '{da_id}' existent."
                        .format(df_id=current_datafield_record.df_fieldnumber.get_value(), 
                                da_id=current_datafield_record.da.get_value()))
                else:
                    self.log("Datafield with id '{df_id}' in dataarea '{da_id}' is already existent."
                        .format(df_id=current_datafield_record.df_fieldnumber.get_value(), 
                                da_id=current_datafield_record.da.get_value()))
                    succeed+=1  
                        
        if succeed < len(df_dictionary.keys()):
            return False
        return True
        
    def change_record(self, datatable, primary_key, change_dictionary):
        old_value = 0
        new_value = 1
        record = self.get_record(datatable, list(primary_key), list(change_dictionary.keys()))
        if not record:
            self.log("WARN: record {rec} doesnot exist in DT{datatable}".format(rec=str(primary_key), datatable=str(datatable)))
            return
        for field in change_dictionary.keys():
            old_new_values = change_dictionary.get(field)
            self.change_value(record, field, old_new_values[old_value], old_new_values[new_value])
            
    def fix(self, runner):
        for packet_function in SQL.keys():
            self.log("executing: %s"%(packet_function.replace("_"," ")))
            sqlpath = self.get_sql_file_path(self.sql_planta_de_dbms, SQL.get(packet_function))
            for query in self.get_queries_from_file(sqlpath):
                self.modify_and_log(query)
    
        self.log("Changing positions in CU of MOD000230 for datafields")
        for datafield in DATAFIELD_DICTIONARY.keys():
            self.change_record(411, datafield, DATAFIELD_DICTIONARY.get(datafield))
        self.log("Creating record DI060099 (Generated) in MOD000230")
        self.create_generated_record(NEW_DFS)
        
        self.log("Migrating 'generated'-values for existing schemas")
        for schema in MIGRATION_EXISTING_SCHEMAS.keys():
            self.change_record(420, schema, MIGRATION_EXISTING_SCHEMAS.get(schema))

        self.log("Migrating 'generated'-values for customer schemas")
        customer_schemas = ppms.db_select("select DI000289 from DT420 where DI001911 not in {planta_licenses}".format(planta_licenses = str(PLANTA_LICENSES)))
        for db_schema in customer_schemas:
            db_schema_record = self.get_record(420, db_schema, ['generated'])
            self.change_value(db_schema_record, 'generated', 0, 1)
            
        return self.success()