Public Class Frm_Calc

    Dim importok As Boolean = False

    Public Type As Calculator.ECalc
    Public Overrides Function AcceptChanged() As Boolean

    End Function
    Public Overrides Function RejectChanged() As Boolean

    End Function
    Public Overrides Function HasChanged() As Boolean

    End Function
    Private Sub Frm_Calc_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.DialogResult = Windows.Forms.DialogResult.Cancel
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Pub.Importsameaddress = False
        Type = Calculator.ECalc.REq
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Type = Calculator.ECalc.Use
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If importok = False AndAlso btImport.Enabled = True Then
            MsgboxE("외부 신재생 생산량을 지정해주세요.")
            Return
        End If
        Type = Calculator.ECalc.All
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Close()
    End Sub

    Private Sub bt_설계개선안_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_설계개선안.Click
        Select Case Prj.UserAuthType
            Case "ADMIN", "BOTH1" '// 우선 제한된 사용자만 설계개선안 검토 가능
                Type = Calculator.ECalc.설계개선안
                Me.DialogResult = Windows.Forms.DialogResult.OK
            Case Else

        End Select

    End Sub

    Private Sub Frm_Calc_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Pub.Importsameaddress = False
        Select Case Prj.UserAuthType
            Case "ADMIN", "BOTH1" '//제한된 사용자만 가능
                bt_설계개선안.Visible = True
            Case Else
                bt_설계개선안.Visible = False
        End Select

        DSET1.tbl_importdata.Clear()
        DSET1.tbl_importdata.AcceptChanges()


        '//import check
        Dim bfind As Boolean = DSET1.tbl_new.Select("기기종류='외부신재생'").Length > 0
        btImport.Enabled = bfind
        importok = False
    End Sub

    Private Sub bt_cancel_Click(sender As System.Object, e As System.EventArgs) Handles bt_cancel.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
    End Sub

    Private Sub btImport_Click(sender As System.Object, e As System.EventArgs) Handles btImport.Click
        '//import data
        Dim Od As New OpenFileDialog
        'Od.InitialDirectory = TemplateDir.FullName
        Od.FileName = Prj.FileName
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            Od.Filter = "템플릿파일(*.TPL,*.TPLX)|*.tpl;*.tplx|모든파일(*.*)|*.*"
        Else
            Od.Filter = "데이터파일(*.ECO,*.ECOX)|*.eco;*.ecox|모든파일(*.*)|*.*"
        End If
        Od.FilterIndex = 0
        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Open_File(Od.FileName)

    End Sub


    Public Function Open_File(ByVal FileName As String, Optional ByVal SyncServer As Boolean = False, Optional checkVersion As Boolean = True, Optional silent As Boolean = False, Optional isNew As Boolean = False) As Boolean

        If SyncServer Then
            If Prj.UserId.ToLower().StartsWith("user") Then
                SyncServer = False
            End If
        End If

        pLog.Add("=======================================")
        pLog.Add(String.Format("Open File = {0}", FileName))
        pLog.Add("=======================================", True)

        Dim PrjIsError As Boolean = False '//160509

        '//파일을 열어서 템플릿이름을 가져온다
        Dim FI As New System.IO.FileInfo(FileName)
        Dim Desbuf() As Byte = {}
        Dim FS As System.IO.Stream
        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조
        If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.16 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 
            Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FI.FullName)

            If Source.Length < 4 Then
                Prj.IsError = True
                MsgboxE("알수없거나 손상된 파일입니다" + vbCrLf + FI.FullName, True)
                Return False
            End If
            pLog.Add("암호화 해제")
            Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})

        Else
            'tpl file
            Desbuf = System.IO.File.ReadAllBytes(FileName)
            ' FS = New IO.FileStream(FileName, IO.FileMode.Open)
        End If

        If FI.Extension.ToLower().EndsWith("x") Then    '//확장자가 x로끝나면 압축된 포맷
            Dim datalen As Integer = BitConverter.ToInt32(Desbuf, 0)
            Dim RealData(Desbuf.Length - 4 - 1) As Byte
            Array.Copy(Desbuf, 4, RealData, 0, RealData.Length)
            Dim DeCompress(datalen - 1) As Byte
            Array.Clear(DeCompress, 0, DeCompress.Length)
            Utility.MiniLZO.Decompress(RealData, DeCompress)
            Array.Resize(Desbuf, DeCompress.Length)
            Array.Clear(Desbuf, 0, Desbuf.Length)
            Array.Copy(DeCompress, Desbuf, Desbuf.Length)
        End If



        FS = New IO.MemoryStream(Desbuf, True)

        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조



        Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
        Dim PrjFileName As String = FileName : Myini.Write("presetting", "filename", Prj.FileName)
        Dim PrjOpened As Boolean = False


        '//세이브파일구조(2)
        Dim PrjSFType As String = STB(Br.ReadBytes(2))
        pLog.Add("File Type = " + Prj.SFType)

        Dim DSImport As New DS()

        Dim PrjUIVersion As String
        Dim PrjLGVersino As String
        Dim Prjname As String
        Dim prjdesc As String
        Dim prjmaketime As String
        Dim prjedittime As String
        Dim PrjPassword As String

        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 

            Select Case Prj.SFType
                Case "00"   '//기본버젼
                    PrjUIVersion = STB(Br.ReadBytes(10))
                    PrjLGVersino = STB(Br.ReadBytes(10))
                    Select Case PrjLGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            PrjLGVersino = StartVersion
                    End Select
                    Select Case PrjUIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            PrjUIVersion = StartVersion
                            PrjUIVersion = StartVersion
                    End Select

                    Prjname = STB(Br.ReadBytes(100))
                    prjdesc = STB(Br.ReadBytes(256))
                    prjmaketime = STB(Br.ReadBytes(19))
                    prjedittime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)


                    Dim DS1Len As Int64 = Br.ReadInt64
                    If DS1Len = 0 Then
                        DS1Len = FS.Length - Br.BaseStream.Position - 2
                    End If
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Nothing
                    Try
                        DS1 = Br.ReadBytes(CInt(DS1Len))
                    Catch ex As Exception
                        Prj.IsError = True
                        MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                    End Try

                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    If Not PrjIsError Then
                        Dim Ms As New IO.MemoryStream(DS1)
                        Try
                            Ms.Position = 0

                            Dim tempds As New DS()
                            tempds.ReadXml(Ms)

                            DSImport.Clear()
                            DSImport.Merge(tempds) '   DSET1.ReadXml(Ms)
                            DSImport.AcceptChanges()
                            Ms.Close()

                            tempds.Dispose()
                        Catch ex As Exception
                            Prj.IsError = True
                            MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "DSImport Open Error")
                        End Try

                    End If

                Case "01"   '//기본버젼(+암호
                    PrjUIVersion = STB(Br.ReadBytes(10))
                    PrjLGVersino = STB(Br.ReadBytes(10))
                    Select Case PrjLGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            PrjLGVersino = StartVersion
                    End Select
                    Select Case PrjUIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            PrjUIVersion = StartVersion
                    End Select
                    Prjname = STB(Br.ReadBytes(100))
                    prjdesc = STB(Br.ReadBytes(256))
                    prjmaketime = STB(Br.ReadBytes(19))
                    prjedittime = STB(Br.ReadBytes(19))
                    PrjPassword = STB(Br.ReadBytes(8)) '//암호에 8바이트할당한다. 즉 8개의문자가가능 한글은 불가로한다
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSImport.Clear() : DSImport.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    Dim Ms As New IO.MemoryStream(DS1)
                    Try

                        Dim tempds As New DS()
                        tempds.ReadXml(Ms)

                        DSImport.Clear()
                        DSImport.Merge(tempds) '  DSET1.ReadXml(Ms)
                        DSImport.AcceptChanges()
                        Ms.Close()

                        tempds.Dispose()
                    Catch ex As Exception
                        MsgBox("파일이 손상되었습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                    End Try


                    PrjIsError = False
                Case Else
                    MsgBox("파일을 불러올 수 없습니다1", MsgBoxStyle.Critical, "불러오기실패")
                    PrjIsError = True
            End Select


        Else
            Select Case Prj.SFType
                Case "10"   '//일반공개버전


                    SyncServer = True ' 2011.06.15 추가 공개버전은 자동적으로 공용코드와 기상코드를 동기화
                    PrjUIVersion = STB(Br.ReadBytes(10))
                    PrjLGVersino = STB(Br.ReadBytes(10))
                    Select Case PrjLGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            PrjLGVersino = StartVersion
                    End Select
                    Select Case PrjUIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            PrjUIVersion = StartVersion
                            PrjUIVersion = StartVersion
                    End Select

                    Prjname = STB(Br.ReadBytes(100))
                    prjdesc = STB(Br.ReadBytes(256))
                    prjmaketime = STB(Br.ReadBytes(19))
                    prjedittime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSImport.Clear() : DSImport.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    Dim Ms As New IO.MemoryStream(DS1)
                    Try
                        Dim tempds As New DS()
                        tempds.ReadXml(Ms)

                        DSImport.Clear()
                        DSImport.Merge(tempds) ' DSET1.ReadXml(Ms)
                        DSImport.AcceptChanges()
                        Ms.Close()

                        tempds.Dispose()

                    Catch ex As Exception
                        MsgBox("파일이 손상되었습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                    End Try

                    PrjIsError = False
                Case Else
                    MsgBox("파일을 불러올 수 없습니다2", MsgBoxStyle.Critical, "불러오기실패")
                    PrjIsError = True
            End Select
        End If

        Br.Close()
        FS.Close()

        pLog.Add(String.Format("Project Name={0},Desc={1},Version={2}", Prj.Name, Prj.Desc, Prj.UIVersion))

        If Not Prj.IsError Then
            PrjOpened = True

            DSET1.tbl_importdata.Clear()

            If DSImport.tbl_Desc.Rows.Count < 1 Then
                MsgBox("해당 파일에 건물개요가 없습니다", MsgBoxStyle.Critical, "불러오기실패")
                Return False
            End If

            If DSET1.tbl_Desc.Rows.Count < 1 Then
                MsgBox("현재 파일에 건물개요가 없습니다", MsgBoxStyle.Critical, "불러오기실패")
                Return False
            End If

            Dim drdesc As DS.tbl_DescRow = DSImport.tbl_Desc.Rows(0)
            Dim drdesc_current As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
           Pub.Importsameaddress = drdesc.buildaddr.Trim() = drdesc_current.buildaddr.Trim()

            For Each dr As DS.tbl_exportdataRow In DSImport.tbl_exportdata
                Dim newdr As DS.tbl_importdataRow = DSET1.tbl_importdata.Newtbl_importdataRow()
                newdr.mon = dr.mon
                newdr.외부전기도입량 = dr.외부전기생산량
                DSET1.tbl_importdata.Addtbl_importdataRow(newdr)
            Next

         
            DSET1.tbl_importdata.AcceptChanges()

            If DSET1.tbl_importdata.Rows.Count < 1 Then
                MsgBox("해당 파일에 외부출력 신재생이 없습니다.", MsgBoxStyle.Critical, "불러오기실패")
                Return False
            End If

            importok = True
            Return True

        Else
            pLog.Add("Open File Error", True)
            Return False
        End If

    End Function



End Class