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

from ppms import ppms
from ppms.migration.packet import *

class UpdateCC(SQLPacket):
    '''Adds calendar weeks to calendar control fields

    This packet adds calendar weeks to the CC template in the global settings 
    that is copied in when you create a new CC field in a dataarea. 

    Additionally existing CC fields are converted to show the calendar
    week if possible.
    '''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 9535

    def fix(self, runner):
        failed_update_statements_411 = 0
        failed_update_statements_333 = 0
        
        select = "select DI040968, DI000306, DI000307, DI000213 from DT411 where DI000221 = 'cc'"    
        listCount = ppms.db_select(select)
        count = 0
                
        rec_333 = ppms.search_record(333, ['d7a12d5d-335c-4c89-801c-38bcd0e43c27'], [51826, 58129])
        templValue = rec_333.template_code.get_value()
               
        for recList in listCount:            
            rec_411 = ppms.search_record(411, [recList[1],int(recList[2])],[40968])            
            old_value = recList[0]
                    
            match = re.search('xaml.*<\W*/\W*StackPanel\W*>', old_value,re.DOTALL)
            matchTempl = re.search('xaml.*<\W*/\W*StackPanel\W*>', templValue,re.DOTALL)
            
            xaml_update = ''
            xaml_template = ''        
            
            if match.group(0).find('\n') != -1:
                xaml_update = match.group(0).replace("\n", "")
            else:
                xaml_update = match.group(0)
                
            if matchTempl.group(0).find('\n') != -1:
                xaml_template = matchTempl.group(0).replace("\n", "")
            else:
                xaml_template = matchTempl.group(0)
                
            xaml_update = xaml_update.replace(" ", "")
            xaml_template = xaml_template.replace(" ", "")
                    
            if xaml_update != xaml_template:                
                count += 1
                self.log(" not update:  " + recList[3] + " " + recList[1] + " " + str(int(recList[2])))         
            else:
                if match:
                    if match.group(0) != self.get_new_xaml_code():
                        start = match.start(0)
                        end = match.end(0)
                        new_value = old_value[:start] + self.get_new_xaml_code() + old_value[end:]                    
                        new_value = new_value.strip()
                        self.log('Update cc-value in cc-box field, DT411 DI000213: ' + str(recList[3]) + " DI000306: " + str(recList[1]) + " DI000307: " + str(int(recList[2])))
                        try:
                            rec_411.df_script_settings.set_value(new_value)                
                            rec_411.save('df_script_settings') 
                        except ppms.DatabaseError as err:
                            self.log(err)
                            self.log('Ignoring for now')
                            failed_update_statements_411 += 1
                    
                        if failed_update_statements_411:
                            return self.fail('Failed %i update statements' % failed_update_statements_411)
          
        if failed_update_statements_411:
            pass
        else:
            if count:                        
                self.log('not update cc-value field, DT411: ' + str(count))
            else:
                self.log('not update cc-value field, DT411 ')
                
        if matchTempl:       
            if matchTempl.group(0) != self.get_new_xaml_code():        
                startT = matchTempl.start(0)
                endT = matchTempl.end(0)
                new_valueT = templValue[:startT] + self.get_new_xaml_code() + templValue[endT:]                    
                new_valueT = new_valueT.strip()                     
                self.log('Update cc-value in cc-template field, DT333')
                try:
                    rec_333.template_code.set_value(new_valueT)                
                    rec_333.save('template_code') 
                except ppms.DatabaseError as err:
                    self.log(err)
                    self.log('Ignoring for now')
                    failed_update_statements_333 += 1
            
                if failed_update_statements_333:
                    return self.fail('Failed %i update statements' % failed_update_statements_333)
            else:
                self.log('not update cc-value in cc-template field, DT333')                 
            
        return self.success()
    
    def get_new_xaml_code(self):
        xaml_code = """xaml = <StackPanel 
                     xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                     xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
                     xmlns:controls = "clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" 
                     xmlns:primitives = "clr-namespace:Microsoft.Windows.Controls.Primitives;assembly=WPFToolkit" 
                     xmlns:vsm = "clr-namespace:System.Windows;assembly=WPFToolkit" 
                     xmlns:src = "clr-namespace:GUI.UserInterface.ModuleControls.CalendarControl;assembly=planta">
                     <StackPanel.Resources>
                      <!--CalendarItem-->
                      <Style x:Key = "calItemStyle" TargetType = "primitives:CalendarItem">
                       <Setter Property = "Margin" Value = "0,3,0,3"/>
                       <Setter Property = "Template">
                        <Setter.Value>
                         <ControlTemplate TargetType = "primitives:CalendarItem">
                          <ControlTemplate.Resources>
                           <!--Start: Data template for header button -->
                           <DataTemplate x:Key = "DayTitleTemplate">
                            <TextBlock FontWeight = "Bold" FontFamily = "Verdana" FontSize = "9.5" Foreground = "#FF333333" HorizontalAlignment = "Center" Text = "{Binding}" Margin = "0,6,0,6" VerticalAlignment = "Center"/>
                           </DataTemplate>
                           <!--End: Data template for header button -->
                          </ControlTemplate.Resources>
                          <Grid Name = "PART_Root">
                           <Grid.Resources>
                            <SolidColorBrush x:Key = "DisabledColor" Color = "#A5FFFFFF"/>
                           </Grid.Resources>
                           <vsm:VisualStateManager.VisualStateGroups>
                            <vsm:VisualStateGroup x:Name = "CommonStates">
                             <vsm:VisualState x:Name = "Normal"/>
                             <vsm:VisualState x:Name = "Disabled">
                              <Storyboard>
                               <DoubleAnimation Storyboard.TargetName = "PART_DisabledVisual" Storyboard.TargetProperty = "Opacity" To = "1" Duration = "0"/>
                              </Storyboard>
                             </vsm:VisualState>
                            </vsm:VisualStateGroup>
                           </vsm:VisualStateManager.VisualStateGroups>
                           <Border BorderBrush = "{TemplateBinding BorderBrush}" BorderThickness = "{TemplateBinding BorderThickness}" Background = "{TemplateBinding Background}" CornerRadius = "1">
                            <Border CornerRadius = "1" BorderBrush = "#FFFFFFFF" BorderThickness = "2">
                             <Grid>
                              <Grid.RowDefinitions>
                               <RowDefinition Height = "Auto"/>
                               <RowDefinition Height = "*"/>
                              </Grid.RowDefinitions>
                              <Grid.ColumnDefinitions>
                               <ColumnDefinition Width = "Auto"/>
                               <ColumnDefinition Width = "Auto"/>
                               <ColumnDefinition Width = "Auto"/>
                              </Grid.ColumnDefinitions>
                              <Grid.Resources>
                               <!--Start: Previous button template -->
                               <ControlTemplate x:Key = "PreviousButtonTemplate" TargetType = "Button">
                                <Grid Cursor = "Hand">
                                 <vsm:VisualStateManager.VisualStateGroups>
                                  <vsm:VisualStateGroup x:Name = "CommonStates">
                                   <vsm:VisualState x:Name = "Normal"/>
                                   <vsm:VisualState x:Name = "MouseOver">
                                    <Storyboard>
                                     <ColorAnimation Storyboard.TargetName = "TextColor" Storyboard.TargetProperty = "Color" To = "#FF73A9D8" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                   <vsm:VisualState x:Name = "Disabled">
                                    <Storyboard>
                                     <DoubleAnimation Storyboard.TargetName = "TextColor" Storyboard.TargetProperty = "Opacity" To = ".5" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                  </vsm:VisualStateGroup>
                                 </vsm:VisualStateManager.VisualStateGroups>
                                 <Rectangle Fill = "#11E5EBF1" Stretch = "Fill" Opacity = "1"/>
                                 <Grid>
                                  <Path Margin = "14,-6,0,0" Height = "10" Width = "6" VerticalAlignment = "Center" HorizontalAlignment = "Left" Stretch = "Fill" Data = "M288.75,232.25 L288.75,240.625 L283,236.625 z">
                                   <Path.Fill>
                                    <SolidColorBrush x:Name = "TextColor" Color = "#FF333333"/>
                                   </Path.Fill>
                                  </Path>
                                 </Grid>
                                </Grid>
                               </ControlTemplate>
                               <!--End: Previous button template -->
                               <!--Start: Next button template -->
                               <ControlTemplate x:Key = "NextButtonTemplate" TargetType = "Button">
                                <Grid Cursor = "Hand">
                                 <vsm:VisualStateManager.VisualStateGroups>
                                  <vsm:VisualStateGroup x:Name = "CommonStates">
                                   <vsm:VisualState x:Name = "Normal"/>
                                   <vsm:VisualState x:Name = "MouseOver">
                                    <Storyboard>
                                     <ColorAnimation Storyboard.TargetName = "TextColor" Storyboard.TargetProperty = "Color" To = "#FF73A9D8" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                   <vsm:VisualState x:Name = "Disabled">
                                    <Storyboard>
                                     <DoubleAnimation Storyboard.TargetName = "TextColor" Storyboard.TargetProperty = "Opacity" To = ".5" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                  </vsm:VisualStateGroup>
                                 </vsm:VisualStateManager.VisualStateGroups>
                                 <Rectangle Fill = "#11E5EBF1" Stretch = "Fill" Opacity = "1"/>
                                 <Grid>
                                  <Path Margin = "0,-6,14,0" Height = "10" Width = "6" VerticalAlignment = "Center" HorizontalAlignment = "Right" Stretch = "Fill" Data = "M282.875,231.875 L282.875,240.375 L288.625,236 z">
                                   <Path.Fill>
                                    <SolidColorBrush x:Name = "TextColor" Color = "#FF333333"/>
                                   </Path.Fill>
                                  </Path>
                                 </Grid>
                                </Grid>
                               </ControlTemplate>
                               <!--End: Next button template -->
                               <!--Start: Header button template -->
                               <ControlTemplate x:Key = "HeaderButtonTemplate" TargetType = "Button">
                                <Grid Cursor = "Hand">
                                 <vsm:VisualStateManager.VisualStateGroups>
                                  <vsm:VisualStateGroup x:Name = "CommonStates">
                                   <vsm:VisualState x:Name = "Normal"/>
                                   <vsm:VisualState x:Name = "MouseOver">
                                    <Storyboard>
                                     <ColorAnimation Storyboard.TargetName = "TextColor" Storyboard.TargetProperty = "Color" To = "#FF73A9D8" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                   <vsm:VisualState x:Name = "Disabled">
                                    <Storyboard>
                                     <DoubleAnimation Storyboard.TargetName = "buttonContent" Storyboard.TargetProperty = "Opacity" To = ".5" Duration = "0"/>
                                    </Storyboard>
                                   </vsm:VisualState>
                                  </vsm:VisualStateGroup>
                                 </vsm:VisualStateManager.VisualStateGroups>
                                 <ContentPresenter x:Name = "buttonContent" Content = "{TemplateBinding Content}" ContentTemplate = "{TemplateBinding ContentTemplate}" Margin = "1,4,1,9" HorizontalAlignment = "{TemplateBinding HorizontalContentAlignment}" VerticalAlignment = "{TemplateBinding VerticalContentAlignment}">
                                  <TextElement.Foreground>
                                   <SolidColorBrush x:Name = "TextColor" Color = "#FF333333"/>
                                  </TextElement.Foreground>
                                 </ContentPresenter>
                                </Grid>
                               </ControlTemplate>
                               <!--End: Header button template -->
                              </Grid.Resources>
                              <!--Start: Previous button content -->
                              <Button x:Name = "PART_PreviousButton" Grid.Row = "0" Grid.Column = "0" Template = "{StaticResource PreviousButtonTemplate}" Height = "20" Width = "28" HorizontalAlignment = "Left" Focusable = "False"/>
                              <!--End: Previous button content -->
                              <!--Start: Header button content -->
                              <Button x:Name = "PART_HeaderButton" Grid.Row = "0" Grid.Column = "1" Template = "{StaticResource HeaderButtonTemplate}" HorizontalAlignment = "Center" VerticalAlignment = "Center" FontWeight = "Bold" FontSize = "10.5" Focusable = "False"/>
                              <!--End: Header button content -->
                              <!--Start: Next button content -->
                              <Button x:Name = "PART_NextButton" Grid.Row = "0" Grid.Column = "2" Height = "20" Width = "28" HorizontalAlignment = "Right" Template = "{StaticResource NextButtonTemplate}" Focusable = "False"/>
                              <!--End: Next button content -->
                              <!--*************************************************************************** -->
                              <!--New for WeekNumbers (Grid.Row & Grid.ColumnSpan lifted from PART_MonthView) -->
                              <StackPanel Grid.Row = "1" Grid.ColumnSpan = "3" Grid.IsSharedSizeScope = "True" Margin = "6,-1,6,6" Orientation = "Horizontal">
                               <Grid Visibility = "{Binding ElementName=PART_MonthView, Path=Visibility}" Background = "AliceBlue">
                                <Grid.Resources>
                                 <Style TargetType = "TextBlock">
                                  <Setter Property = "FontFamily" Value = "Verdana"/>
                                  <Setter Property = "FontWeight" Value = "Bold"/>
                                  <Setter Property = "FontSize" Value = "9.5"/>
                                  <Setter Property = "Foreground" Value = "#FF333333"/>
                                  <Setter Property = "HorizontalAlignment" Value = "Center"/>
                                  <Setter Property = "VerticalAlignment" Value = "Center"/>
                                 </Style>
                                 <Style TargetType = "src:WeekNumber" BasedOn = "{StaticResource {x:Type TextBlock}}">
                                  <Setter Property = "FontWeight" Value = "Normal"/>
                                  <Setter Property = "FontSize" Value = "9.5"/>
                                 </Style>
                                </Grid.Resources>
                                <Grid.RowDefinitions>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedTitleHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                </Grid.RowDefinitions>
                                <TextBlock Grid.Row = "0" Text = "CalendarWeekHeader"/>
                                <src:WeekNumber Grid.Row = "1" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                                <src:WeekNumber Grid.Row = "2" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                                <src:WeekNumber Grid.Row = "3" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                                <src:WeekNumber Grid.Row = "4" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                                <src:WeekNumber Grid.Row = "5" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                                <src:WeekNumber Grid.Row = "6" Calendar = "{Binding RelativeSource={RelativeSource AncestorType=controls:Calendar}}"/>
                               </Grid>
                               <!--End of New for WeekNumbers                                                  -->
                               <!--*************************************************************************** -->
                               <!--Plus SharedSizeGroup added to next Grid                                     -->
                               <!--Start: Month Content Grid -->
                               <Grid x:Name = "PART_MonthView" Visibility = "Visible">
                                <Grid.RowDefinitions>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedTitleHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                 <RowDefinition Height = "Auto" SharedSizeGroup = "SharedItemHeight"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                 <ColumnDefinition Width = "Auto"/>
                                </Grid.ColumnDefinitions>
                               </Grid>
                               <!--End: Month Content Grid -->
                               <!--New for WeekNumbers -->
                              </StackPanel>
                              <!--End of new for WeekNumbers -->
                              <!--End: Year Content Grid -->
                              <Grid x:Name = "PART_YearView" Grid.Row = "1" Grid.ColumnSpan = "3" Visibility = "Hidden" Margin = "6,-3,7,6">
                               <Grid.RowDefinitions>
                                <RowDefinition Height = "Auto"/>
                                <RowDefinition Height = "Auto"/>
                                <RowDefinition Height = "Auto"/>
                               </Grid.RowDefinitions>
                               <Grid.ColumnDefinitions>
                                <ColumnDefinition Width = "Auto"/>
                                <ColumnDefinition Width = "Auto"/>
                                <ColumnDefinition Width = "Auto"/>
                                <ColumnDefinition Width = "Auto"/>
                               </Grid.ColumnDefinitions>
                              </Grid>
                              <!--End: Year Content Grid -->
                             </Grid>
                            </Border>
                           </Border>
                           <Rectangle x:Name = "PART_DisabledVisual" Opacity = "0" Visibility = "Collapsed" Stretch = "Fill" StrokeThickness = "1" RadiusX = "2" RadiusY = "2" Stroke = "{StaticResource DisabledColor}" Fill = "{StaticResource DisabledColor}"/>
                          </Grid>
                          <ControlTemplate.Triggers>
                           <Trigger Property = "IsEnabled" Value = "False">
                            <Setter TargetName = "PART_DisabledVisual" Property = "Visibility" Value = "Visible"/>
                           </Trigger>
                           <DataTrigger Value = "Year">
                            <DataTrigger.Binding>
                             <Binding Path = "DisplayMode">
                              <Binding.RelativeSource>
                               <RelativeSource Mode = "FindAncestor" AncestorType = "{x:Type controls:Calendar}"/>
                              </Binding.RelativeSource>
                             </Binding>
                            </DataTrigger.Binding>
                            <Setter TargetName = "PART_MonthView" Property = "Visibility" Value = "Hidden"/>
                            <Setter TargetName = "PART_YearView" Property = "Visibility" Value = "Visible"/>
                           </DataTrigger>
                           <DataTrigger Value = "Decade">
                            <DataTrigger.Binding>
                             <Binding Path = "DisplayMode">
                              <Binding.RelativeSource>
                               <RelativeSource Mode = "FindAncestor" AncestorType = "{x:Type controls:Calendar}"/>
                              </Binding.RelativeSource>
                             </Binding>
                            </DataTrigger.Binding>
                            <Setter TargetName = "PART_MonthView" Property = "Visibility" Value = "Hidden"/>
                            <Setter TargetName = "PART_YearView" Property = "Visibility" Value = "Visible"/>
                           </DataTrigger>
                          </ControlTemplate.Triggers>
                         </ControlTemplate>
                        </Setter.Value>
                       </Setter>
                      </Style>
                     </StackPanel.Resources>
                     <controls:Calendar CalendarItemStyle = "{StaticResource calItemStyle}" Name = "Calendar" Margin = "0,-3,1,-2"/>
                    </StackPanel>"""

        return xaml_code