Imports Windows.UI.Xaml.Navigation
Imports Windows.UI.Xaml.Media.Imaging
Imports Windows.UI.Xaml.Media
Imports Windows.UI.Xaml.Input
Imports Windows.UI.Xaml.Data
Imports Windows.UI.Xaml.Controls.Primitives
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml
Imports Windows.UI.Core
Imports Windows.Foundation.Collections
Imports Windows.Foundation
Imports System.Runtime.InteropServices.WindowsRuntime
Imports System.Linq
Imports System.IO
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Collections.Generic
Imports System
Imports C1.Xaml.InputPanel
Imports C1.Xaml.FlexGrid
Imports InputPanelSamples.Common

' The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Partial Public NotInheritable Class IntegrationC1FlexGrid
    Inherits Page
    Private _cellFactory As MyCellFactory
    Private _viewDetailCommand As ICommand
    Public ReadOnly Property ViewDetailCommand() As ICommand
        Get
            Dim action As Action = AddressOf NavigateToDetails
            If _viewDetailCommand IsNot Nothing Then
                Return _viewDetailCommand
            End If
            _viewDetailCommand = New DelegateCommand(action, FlexGrid.SelectedItem IsNot Nothing)
            Return _viewDetailCommand
        End Get
    End Property
    Public Sub New()
        InitializeComponent()

        If Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
            IntegrationToC1FlexGrid()
            Me.DataContext = Me
        Else
            InitalizeFlexGrid()
        End If
    End Sub

    Private Sub IntegrationToC1FlexGrid()
        Data.LoadEmployee()
        FlexGrid.ItemsSource = New Data().EmployeeObservable
        FlexGrid.SelectionMode = C1.Xaml.FlexGrid.SelectionMode.Row
        FlexGrid.SelectedIndex = 0
    End Sub

    Private Sub InitalizeFlexGrid()
        Data.Load()
        FlexGrid.ItemsSource = New Data().CustomerObservable
        AddHandler FlexGrid.Loaded, AddressOf FlexGrid_Loaded
        FlexGrid.AllowMerging = AllowMerging.Cells
        _cellFactory = New MyCellFactory()
        FlexGrid.CellFactory = _cellFactory
        AddHandler FlexGrid.SelectionChanging, AddressOf FlexGrid_SelectionChanging
        AddHandler FlexGrid.SortedColumn, AddressOf FlexGrid_SortedColumn
        AddNewRowToFlexGrid(FlexGrid)
        FlexGrid.MergeManager = New MyMergeManager()
    End Sub

    Private Sub FlexGrid_Loaded(sender As Object, e As RoutedEventArgs)
        FlexGrid.AutoSizeColumns(1, FlexGrid.Columns.Count - 1, 10)
    End Sub

    Private Sub NavigateToDetails()
        Dim employee As Employee = TryCast(FlexGrid.SelectedItem, Employee)
        If employee IsNot Nothing Then
            Dim frame As Object = TryCast(Window.Current.Content, Frame)
            If frame IsNot Nothing Then
                frame.Navigate(GetType(InputPanelCurrentItem), employee)
            Else
                Me.Frame.Navigate(GetType(InputPanelCurrentItem), employee)
            End If
        End If
    End Sub

    Private Sub AddNewRowToFlexGrid(flexGrid As C1FlexGrid)
        Dim i As Integer = flexGrid.Rows.Count - 1
        While i >= 0
            Dim rw As New Row()
            rw.AllowMerging = True
            flexGrid.Rows.Insert(i + 1, rw)
            rw.Height = 0.1
            i = i - 1
        End While
        _cellFactory.expandedList = New List(Of Integer)()
    End Sub

    Private Sub FlexGrid_SortedColumn(sender As Object, e As CellRangeEventArgs)
        Dim flexGrid As C1FlexGrid = TryCast(sender, C1FlexGrid)
        AddNewRowToFlexGrid(flexGrid)
    End Sub

    Private Sub FlexGrid_SelectionChanging(sender As Object, e As CellRangeEventArgs)
        Dim inputPanel As C1InputPanel = Nothing
        GetInputPanelElement(e.Panel, inputPanel)
        If inputPanel IsNot Nothing AndAlso e.CellRange.Row Mod 2 = 1 Then
            e.Cancel = True
        End If
    End Sub

    Sub GetInputPanelElement(obj As DependencyObject, ByRef element As C1InputPanel)
        If obj IsNot Nothing Then
            Dim count As Integer = VisualTreeHelper.GetChildrenCount(obj)
            Dim i As Integer = 0
            While i < count
                Dim child As DependencyObject = VisualTreeHelper.GetChild(obj, i)
                Dim inputPanel As C1InputPanel = TryCast(child, C1InputPanel)
                If inputPanel IsNot Nothing Then
                    element = inputPanel
                    Exit While
                Else
                    GetInputPanelElement(child, element)
                End If
                i += 1
            End While
        End If
    End Sub
End Class

Public Class MyMergeManager
    Implements IMergeManager
    Public Function GetMergedRange(grid As C1FlexGrid, cellType As CellType, range As CellRange) As CellRange Implements IMergeManager.GetMergedRange
        If grid.Rows(range.Row).DataItem Is Nothing Then
            If cellType = CellType.Cell AndAlso range.Column >= 0 AndAlso range.Column < grid.Columns.Count Then
                range.Column = 0
                range.Column2 = grid.Columns.Count - 1
            End If
        End If
        Return range
    End Function
End Class

Public Class MyCellFactory
    Inherits CellFactory
    Private _gr As Row
    Private _fg As C1FlexGrid
    Shared _bmpExpanded As ImageSource, _bmpCollapsed As ImageSource
    Public expandedList As New List(Of Integer)()

    Public Sub New()
        _bmpExpanded = ImageCell.GetImageSource("Expanded.png")
        _bmpCollapsed = ImageCell.GetImageSource("Collapsed.png")
    End Sub

    Public Overrides Sub CreateCellContent(grid As C1FlexGrid, bdr As Border, rng As CellRange)
        MyBase.CreateCellContent(grid, bdr, rng)
        If _fg Is Nothing Then
            _fg = grid
        End If

        If _fg.Rows(rng.Row).DataItem IsNot Nothing Then
            If rng.Column = 0 Then
                Dim customer As Customer = (TryCast(grid.Rows(rng.Row).DataItem, Customer))

                If customer IsNot Nothing Then
                    bdr.Child = Nothing
                    Dim _nodeImage As Image
                    _gr = grid.Rows(rng.Row)
                    _nodeImage = New Image()

                    If expandedList.Contains(rng.Row) Then
                        _nodeImage.Source = _bmpExpanded
                    Else
                        _nodeImage.Source = _bmpCollapsed
                    End If

                    _nodeImage.Width = 9
                    _nodeImage.Height = 9
                    _nodeImage.VerticalAlignment = VerticalAlignment.Center
                    _nodeImage.Stretch = Stretch.None
                    bdr.Child = _nodeImage
                    AddHandler _nodeImage.PointerPressed, AddressOf _nodeImage_PointerPressed
                Else
                    expandedList.Remove(rng.Row)
                    _fg.Rows(rng.Row + 1).Height = 0.1
                End If
            End If
        ElseIf rng.Column = 0 AndAlso rng.ColumnSpan > 1 Then
            Dim customer As Customer = (TryCast(grid.Rows(rng.Row - 1).DataItem, Customer))
            Dim panel As New C1InputPanel()
            AddHandler panel.Tapped, AddressOf panel_Tapped
            panel.CurrentItem = customer
            grid.Rows(rng.Row).Tag = grid.Rows(rng.Row - 1).ActualHeight * (grid.Columns.Count + 1) * 1.4
            bdr.Child = panel
            bdr.Padding = New Thickness(1)
            grid.Rows(rng.Row).IsReadOnly = True
        End If
    End Sub

    Sub panel_Tapped(sender As Object, e As TappedRoutedEventArgs)
        e.Handled = True
    End Sub

#Region "Handle Mouse Down event for toggling the expand/Collapse icon and change the visibility of Child Row"
    Sub _nodeImage_PointerPressed(sender As Object, e As PointerRoutedEventArgs)
        Dim _row As Integer = Grid.GetRow(((TryCast(VisualTreeHelper.GetParent(TryCast(e.OriginalSource, Image)), Border))))
        SetExpandCollapse(_row, sender)
    End Sub

    Public Sub SetExpandCollapse(_row As Integer, sender As Object)
        Dim image As Image = TryCast(sender, Image)
        If expandedList.Contains(_row) Then
            _fg.Rows(_row + 1).Height = 0.1
            expandedList.Remove(_row)
            image.Source = _bmpCollapsed
        Else
            If _fg.Rows(_row + 1).Tag IsNot Nothing Then
                _fg.Rows(_row + 1).Height = Double.Parse(_fg.Rows(_row + 1).Tag.ToString())
            End If
            expandedList.Add(_row)
            image.Source = _bmpExpanded
        End If
    End Sub

#End Region
End Class

Public MustInherit Class ImageCell
    Inherits StackPanel
    Private _imgSrc As ImageSource

    Public Sub New(row As Row)
        If _imgSrc Is Nothing Then
            _imgSrc = GetImageSource(GetImageResourceName())
        End If
        Orientation = Orientation.Horizontal
        Dim img As New Image()
        img.Source = _imgSrc
        img.Width = 25
        img.Height = 15
        img.VerticalAlignment = VerticalAlignment.Center
        img.Stretch = Stretch.None
        Children.Add(img)
    End Sub

    Public MustOverride Function GetImageResourceName() As String

    Public Shared Function GetImageSource(imageName As String) As ImageSource
        Dim _baseUri As New System.Uri("ms-appx:///InputPanelSamplesLib/")
        Return New BitmapImage(New System.Uri(_baseUri, String.Format("Assets/{0}", imageName)))
    End Function
End Class