<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/master.Master" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<%@ Import Namespace="MKInsight.Online.Core.Security" %>
<%@ Import Namespace="AuditVision.Online.DataServices" %>
<%@ Import Namespace="MKInsight.Online.Shared" %>
<%@ Import Namespace="MKInsight.Online.Login" %>
<%@ Import Namespace="MK.Core" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="AuditVision.Online.DataServices.Compression" %>
<%@ Import Namespace="System.Web.Hosting" %>
<%@ Import Namespace="MK.Core.PasswordEncoding" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style type="text/css">
        span {
            color:white;
        }

        .box {
            position: fixed;
            margin-left: -150px;
            margin-top: -150px;
            top: 50%;
            left: 48.1%;
        }
    </style>

    <script runat="server" language="vb">

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


            If Not Page.IsPostBack Then
                txt_AccountName.Focus()
                StringTable.Start()
                Localise()
            End If

        End Sub

        Private Sub Localise()
            Dim st As StringTableDelegate = StringTable.CreateDelegate

            lbl_AcountName.Text = st("AccountName:")
            lbl_AccountPassword.Text = st("AccountPassword_Colon")
            lbl_UploadFile.Text = st("TerminologyFile")
            lbl_Title.Text = st("TerminologyUpdatePageTitle")
            lbl_FileInfo.Text = st("TerminologyFileInfo")
            btn_Update.Text = st("Update")

            RAccount.ErrorMessage = st("InvalidAccountIDcheckagain")
            RPassword.ErrorMessage = st("InvalidPasswordPleaseCheckYourEntryandTryAgain")

        End Sub

        Protected Sub OnUpdateTerminology(sender As Object, e As EventArgs) Handles btn_Update.Click

            If Not ValidateAccount() Then
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Warning, StringTable.Text("TerminologyUpdateValidateAccountMessage"))
                Return
            End If

            If Not ValidateDictionaryFile() Then
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Warning, StringTable.Text("EnterValidTerminologyFile"))
                Return
            End If

            If Not ValidateDictionaryFileName() Then
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Warning, StringTable.Text("EnterValidTerminologyFile"))
                Return
            End If

            Try

                UpdateOverrideFile()

                Helper.AlertMessage(dv_Alert, Helper.AlertType.OK, StringTable.Text("EnterValidTerminologyFileSuccessfully"))

            Catch uex As UnauthorizedAccessException
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Warning, StringTable.Text("TerminologyFileAccessWarringMessage"))

            Catch ex As Exception
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Error, ex.ToString())
            End Try

        End Sub

        Private Sub UpdateOverrideFile()

            Try
                Dim folder As String = ServerConfig.FindResourcePath("overrideDictionaryRoot", "overrides\dicts")

                Dim fullPath As String = Path.Combine(folder, txt_AccountName.Text)

                If Not Directory.Exists(fullPath) Then Directory.CreateDirectory(fullPath)

                u_File.SaveAs(Path.Combine(fullPath, New FileInfo(u_File.PostedFile.FileName).Name))

            Catch uex As UnauthorizedAccessException
                Throw
            Catch ex As Exception
                Throw
            End Try

        End Sub

        Private Function ValidateAccount() As Boolean
            Dim hashPassword As String = CreateSHA512(txt_AccountPassword.Text)

            Dim configObj As ServerConfig = ServerConfig.Instance

            If IsNothing(configObj.Accounts.Item(txt_AccountName.Text)) Then Return False

            If TestSHA512(configObj.Accounts.Item(txt_AccountName.Text).PasswordHash, hashPassword) Then Return False

            Return True
        End Function

        Private Function ValidateDictionaryFileName() As Boolean

            If Not u_File.HasFile Then Return False

            Dim fileName As String = u_File.PostedFile.FileName

            Dim fInfo As New FileInfo(fileName)

            If fInfo.Extension <> ".mkox" Then
                Helper.AlertMessage(dv_Alert, Helper.AlertType.Warning, StringTable.Text("EnterValidTerminologyFile"))
                Return False
            End If

            Try
                Dim c As New CultureInfo(fInfo.Name.Split("."c)(0))
            Catch ex As Exception
                Return False
            End Try

            Return True
        End Function

        Private Function ValidateDictionaryFile() As Boolean
            If Not u_File.HasFile Then Return False

            Return LoadDictionaryStream(u_File.FileContent)
        End Function

        Private Function Encode(buffer As Byte()) As String
            Dim hexPairs As String = ""

            For Each b As Byte In buffer
                hexPairs += Convert.ToString(b, 16).PadLeft(2, "0"c)

            Next

            Return hexPairs.ToUpperInvariant()

        End Function

        Private Function LoadDictionaryStream(baseStream As Stream) As Boolean

            Try

                Dim cStream As InflaterInputStream = New InflaterInputStream(baseStream)
                Dim reader As StreamReader = New StreamReader(cStream)

                Do While True
                    Dim line As String = reader.ReadLine()
                    If line Is Nothing OrElse line = "EOF" Then Exit Do

                    Dim parts As String() = line.Replace(Constant.RECORD_CHAR, Environment.NewLine).Split(Constant.UNIT_CHAR)
                    If parts.Length <> 2 Then Continue Do

                Loop

                Return True

            Catch ex As Exception
                Return False
            End Try

        End Function

        Private Function MapRelativePath(relativePath As String) As String
            Return Path.Combine(HostingEnvironment.ApplicationPhysicalPath, relativePath.Replace("/"c, "\"c).Trim("\"c))

        End Function

    </script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cm" runat="server">

    <div role="alert" id="dv_Alert" runat="server" style="margin-top: 5px;">
    </div>
<div style="padding-left:20px;">

    <div>
        <h2>
            <asp:Label ID="lbl_Title" runat="server"></asp:Label></h2>
    </div>
    <br />

    <table>
        <tr>
            <td>
                <asp:Label ID="lbl_AcountName" runat="server"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txt_AccountName" runat="server" Width="300px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_AccountPassword" runat="server"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txt_AccountPassword" runat="server" TextMode="Password" Width="300px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_UploadFile" runat="server"></asp:Label>
            </td>
            <td>
                <asp:FileUpload runat="server" ID="u_File" Width="300px" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lbl_FileInfo" runat="server" Font-Italic="True" Font-Size="XX-Small"></asp:Label>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <hr />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btn_Update" runat="server" ForeColor="Black" />
            </td>
        </tr>
    </table>

    <cc1:ValidatorCalloutExtender ID="v_Account" runat="server" TargetControlID="RAccount">
    </cc1:ValidatorCalloutExtender>
    <asp:RequiredFieldValidator ID="RAccount" runat="server" ControlToValidate="txt_AccountName"
        Display="None" SetFocusOnError="True"></asp:RequiredFieldValidator>

    <cc1:ValidatorCalloutExtender ID="v_Password" runat="server" TargetControlID="RPassword">
    </cc1:ValidatorCalloutExtender>
    <asp:RequiredFieldValidator ID="RPassword" runat="server" ControlToValidate="txt_AccountPassword"
        Display="None" SetFocusOnError="True"></asp:RequiredFieldValidator>
    </div>
</asp:Content>
