Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.ExpressApp.Editors
Imports DevExpress.XtraSpreadsheet
Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.Spreadsheet
Imports DevExpress.XtraPrinting
Imports DevExpress.Persistent.BaseImpl

Public Class BallanceVC
    Inherits SISBusiness.Module.BallanceVC
    Dim _WaitFormClass As New WaitFormClass
    Private _SpreadsheetControl As SpreadsheetControl
    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()

        AddHandler DoWork, AddressOf _WaitFormClass.DoWork
        AddHandler InitWork, AddressOf _WaitFormClass.Initwork
        AddHandler FinalWork, AddressOf _WaitFormClass.Finalwork

        If View.Id = "BallanceHeader_DetailView" Then
            Dim _DetailView As DetailView = TryCast(View, DetailView)
            Dim _SpreadXML_ViewItem As ViewItem = _DetailView.FindItem("SpreadXML")
            If _SpreadXML_ViewItem IsNot Nothing Then
                AddHandler _SpreadXML_ViewItem.ControlCreated, AddressOf _SpreadXML_ViewItem_ControlCreated

                AddHandler Frame.GetController(Of ModificationsController).SaveAction.Executing, AddressOf SaveAction_Executing
            End If
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()

        RemoveHandler DoWork, AddressOf _WaitFormClass.DoWork
        RemoveHandler InitWork, AddressOf _WaitFormClass.Initwork
        RemoveHandler FinalWork, AddressOf _WaitFormClass.Finalwork
    End Sub

    Private Sub _SpreadXML_ViewItem_ControlCreated(sender As Object, e As EventArgs)
        Dim _BallanceHeader As BallanceHeader = TryCast(View.SelectedObjects(0), BallanceHeader)
        Dim _ItemControl As Object = TryCast(sender, ViewItem).Control
        Dim _SpreadSimpleUserControl As SpreadSimpleUserControl = TryCast(_ItemControl, SpreadSimpleUserControl)

        _SpreadsheetControl = TryCast(_ItemControl, SpreadSimpleUserControl).SpreadsheetControl1

        If _BallanceHeader IsNot Nothing Then
            If _BallanceHeader.SpreadFileData IsNot Nothing Then
                Dim _FilePath As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _BallanceHeader.SpreadFileData.FileName)
                Dim _Stream As System.IO.Stream = New System.IO.FileStream(_FilePath, System.IO.FileMode.Create)
                _BallanceHeader.SpreadFileData.SaveToStream(_Stream)
                _Stream.Close()

                Dim _StreamFile = New System.IO.FileStream(_FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
                Dim _StreamReader As New System.IO.StreamReader(_StreamFile)
                Dim workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document
                _StreamFile.Seek(0, System.IO.SeekOrigin.Begin)
                workbook.LoadDocument(_StreamFile, DevExpress.Spreadsheet.DocumentFormat.OpenXml)
                _StreamFile.Close()

                InitSpread(_BallanceHeader)
            End If
        End If
    End Sub

    Private Sub SaveAction_Executing(sender As Object, e As CancelEventArgs)
        Dim _BallanceHeader As BallanceHeader = TryCast(View.SelectedObjects(0), BallanceHeader)
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

        If _SpreadsheetControl IsNot Nothing Then

            '// TESZT
            FormatSpread(_BallanceHeader)

            Dim _FilePath As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "BALANCE.XML")
            Dim _Stream As System.IO.Stream = New System.IO.FileStream(_FilePath, System.IO.FileMode.Create)
            _SpreadsheetControl.Document.SaveDocument(_Stream, DevExpress.Spreadsheet.DocumentFormat.OpenXml)
            _Stream.Close()

            Dim _StreamFile = New System.IO.FileStream(_FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim _StreamReader As New System.IO.StreamReader(_StreamFile)
            _StreamFile.Seek(0, System.IO.SeekOrigin.Begin)

            Dim _FileData As FileData
            _FileData = _ocur.CreateObject(Of FileData)()

            _FileData.LoadFromStream("BALANCE.XML", _StreamFile)

            _BallanceHeader.SpreadFileData = _FileData
        End If
    End Sub
    Private Sub InitSpread(_BallanceHeader As BallanceHeader)
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _BallanceSpreadCustomFunctions As New BallanceSpreadCustomFunctions(_BallanceHeader, _ocur)
        Dim _workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document

        If (Not _workbook.CustomFunctions.Contains(_BallanceSpreadCustomFunctions.Name)) Then
            _workbook.CustomFunctions.Add(_BallanceSpreadCustomFunctions)
        End If
        '// cégjegyzékszám
        Dim _worksheet As Worksheet = _workbook.Worksheets("Borító")
        _worksheet.Cells("A3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 1, 1))
        _worksheet.Cells("B3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 2, 1))
        _worksheet.Cells("D3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 3, 1))
        _worksheet.Cells("E3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 4, 1))
        _worksheet.Cells("G3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 5, 1))
        _worksheet.Cells("H3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 6, 1))
        _worksheet.Cells("I3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 7, 1))
        _worksheet.Cells("J3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 8, 1))
        _worksheet.Cells("K3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 9, 1))
        _worksheet.Cells("L3").SetValue(Mid(Replace(_BallanceHeader.CustomersFrom.CompanyRegistrationNumber, "-", ""), 10, 1))

        _worksheet = _workbook.Worksheets("Eszközök A")
        _worksheet.Cells("R11").SetValue(Format(_BallanceHeader.TrialBalanceHeaderBefore.DateTo.Date, "yyyy.MM.dd"))
        _worksheet.Cells("T11").SetValue(Format(_BallanceHeader.TrialBalanceHeader.DateTo.Date, "yyyy.MM.dd"))
    End Sub
    Private Sub FormatSpread(_BallanceHeader As BallanceHeader)

        Dim _workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document
        Dim _worksheet As Worksheet = _workbook.Worksheets("Borító")
        Dim _worksheet_range As DevExpress.Spreadsheet.Range

        _worksheet_range = _worksheet.GetUsedRange()

        '_worksheet.Rows.Remove(_worksheet_range.RowCount + 1, 999999999)

        _worksheet.Cells("B14").SetValue(_BallanceHeader.CustomersFrom.FullName)
        _worksheet.Cells("B15").SetValue(_BallanceHeader.CustomersFrom.Address1.ZipPostal & ". " & _BallanceHeader.CustomersFrom.Address1.City & ", " & _BallanceHeader.CustomersFrom.Address1.Street)
        _worksheet.Cells("B20").SetValue("Beszámolási időszak:    " & Format(_BallanceHeader.TrialBalanceHeader.DateFrom.Date, "yyyy.MM.dd") & " - " & Format(_BallanceHeader.TrialBalanceHeader.DateTo.Date, "yyyy.MM.dd"))
        _worksheet.Cells("B17").SetValue(Format(_BallanceHeader.TrialBalanceHeader.DateTo.Date, "yyyy.MM.dd") & "-i mérleg fordulónapi")


    End Sub

    Private Sub aSpreadPrintPreview_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aSpreadPrintPreview.Execute
        Dim _workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document

        If _workbook IsNot Nothing Then

            Using printingSystem As New PrintingSystem()
                Using link As New PrintableComponentLink(printingSystem)
                    link.Component = _workbook
                    link.CreateDocument()
                    link.ShowPreviewDialog()
                End Using
            End Using
        End If
    End Sub

    Private Sub aSpreadImportXML_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aSpreadImportXML.Execute
        Dim openFileDialog1 As New Windows.Forms.OpenFileDialog()

        openFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        openFileDialog1.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"
        openFileDialog1.FilterIndex = 1
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            _SpreadsheetControl.LoadDocument(openFileDialog1.FileName, DevExpress.Spreadsheet.DocumentFormat.OpenXml)
        End If
    End Sub

    Private Sub aSpreadExportXML_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aSpreadExportXML.Execute
        Dim openFileDialog1 As New Windows.Forms.SaveFileDialog()

        openFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        openFileDialog1.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"
        openFileDialog1.FilterIndex = 1
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            _SpreadsheetControl.SaveDocument(openFileDialog1.FileName, DevExpress.Spreadsheet.DocumentFormat.OpenXml)
        End If
    End Sub

    Private Sub aSpreadRecalculate_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aSpreadRecalculate.Execute
        Dim _workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document
        _workbook.Calculate()
    End Sub
End Class
