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

from ppms.migration.packet import *
       
class PortSyntaxHighlightingDI(SQLPacket):
    '''Port a new DI necessary for the new syntax highlighting'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11271
    
    FNAME = 'wi11271_syntax_highlighting.sql'
    
    def fix(self, runner):
        path = self.get_sql_file_path(self.sql_planta_de_dbms, self.FNAME)
        for query in self.get_queries_from_file(path, encoding='utf-8'):
            self.modify_and_log(query)
        
        return self.success()
        
class SwapValuerangeDI(SQLPacket):
    '''Use the new syntax highlighting DI for valueranges'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11271

    def fix(self, runner):
        # I would love to do this with a DTP record, but there appears to be
        # a problem changing primary keys in migration mode
        SQL = "UPDATE DT411 SET DI041036 = 'html_valuerange', DI000213 = '062333' WHERE DI000306 = '027139' AND DI000307 = '104712'"
    
        if self.modify_and_log(SQL) == 1:
            return self.success()
            
        return self.fail()
        
class UpdateIronPythonHTMLField(MigratePythonPacket):
    '''Change the IronPython field that generates the syntax highlighted VR code'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11271

    def fix(self, runner):
        BEFORE_HASH = '05fc13bc0136fd3e7f83d1d2454c5cb2'
        AFTER_HASH = '2c5fc6fb68df4eb88fdc8bfdf4333b0f'
    
        fixfunc = lambda _: """# coding: latin-1
import clr
import sys

clr.AddReference('System.Windows.Forms')

from System.Windows.Forms import WebBrowser

wb = WebBrowser()
wb.DocumentText = df.DataArea.ChildrenDF[df.DataArea.Customizing.get_df_by_name('html_valuerange')].GetValue[str]()
        
ctl = wb"""
    
        if self.migrate_python(BEFORE_HASH, AFTER_HASH, 
                               self.CU_TYPE_IRONPYTHON, ['027139', 716659],
                               fixfunc):
            return self.success()
            
        return self.fail()