<%@ Page Language="C#" ContentType="text/html" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  Log logger;// 
  private void Page_Load(object sender, EventArgs e)
  {
    logger = new Log(Server.MapPath(""));
    Osa.Util.OsaRequestInfo req = new Osa.Util.OsaRequestInfo(Request);
    string msg = string.Empty;

    if (!Helper.UISession.Create(req, Request.PhysicalApplicationPath, ref msg))
    {
      bool HTMLerrorpage = false;

      for (int i = 0; i < Request.Headers.AllKeys.Length; i++)
      {
        if (string.Compare(Request.Headers.AllKeys[i], "X-BC-Use-Alternative", true) == 0)
        {
          HTMLerrorpage = true;
        }
      }
      logger.DebugLog("is html error: " + HTMLerrorpage.ToString());
      logger.DebugLog("msg: " + msg);
      if (HTMLerrorpage)
      {
        Response.Redirect(string.Format("FatalErrorHtml.aspx?msg={0}", msg));
      }
      else
      {
        Response.Redirect(string.Format("FatalError.aspx?msg={0}", msg));
      }
      return;
    }

    // Set custom fields
    Helper.UISession s = Helper.UISession.Get(req.GetUISessionID());
    s.css_file = req.GetBC_Resolution();
    s.workMode = Request.Params["mode"];

    //SSO
    //credSSO =  s.GetUserInfo(req);

    //PROPERTY_TYPE[] prp = new PROPERTY_TYPE[4];
    //PROPERTY_TYPE p1 = new PROPERTY_TYPE();  
    //p1.sysname = "display-name";
    //p1.Value = "sam ng";
    //prp[0] = p1;

    //PROPERTY_TYPE p2 = new PROPERTY_TYPE();  
    //p2.sysname = "login-name";
    //p2.Value = "admin";
    //prp[1] = p2;
    //PROPERTY_TYPE p3 = new PROPERTY_TYPE();  
    //p3.sysname = "secure-key";
    //p3.Value = "password";
    //prp[2] = p3;
    //PROPERTY_TYPE p4 = new PROPERTY_TYPE();  
    //p4.sysname = "email-address";
    //p4.Value = "sam@faxcore.com";
    //prp[3] = p4;
    //credSSO.metadata = prp;

    //if (credSSO.metadata.Length>1)
    //{
    //  Session["SSO"] = credSSO;
    //}

    //logger.DebugLog("SSO Metadata count: "+ credSSO.metadata.Length.ToString());

    // Redirect to the ready page.
    const string ERRORPAGE = "ErrorBW.aspx";
    const string MAINPAGE = "~/fxMainMenu.aspx";
    const string HTMLBROWSERNAME = "NetFront";

    string url = ERRORPAGE;

    if (Request.UserAgent.Contains(HTMLBROWSERNAME))
    {
      url = MAINPAGE;
    }
    else
    {
      for (int i = 0; i < Request.Headers.AllKeys.Length; i++)
      {
        if (string.Compare(Request.Headers.AllKeys[i], "X-BC-Alternative", true) == 0)
        {
          // Check whether the HTML browser is available.
          if (Request.Headers.Get(i).IndexOf(HTMLBROWSERNAME) > -1)
          {
            // Navigate to the page for NetFront
            Int64 loginID = SSOLogin(hiddenUser.Value.Trim(), string.Empty, hiddenPwd.Value.Trim());
            if (loginID>2)
            {
              url = MAINPAGE;
              break;
            }
            else
            {
              url = "~/login.aspx";
            }
          }
        }
      }
    }
    Response.Redirect(url, false);
  }

  private Int64 SSOLogin(string username, string email, string secretKey)
  {
    Int64 uid = 0;
    string pwd = secretKey;//DecryptPasswordEncryptedBySepialine(secretKey, "", "");
    FXAPI.wfApi FXapi = new FXAPI.wfApi();
    //FXDIS.wfDispatcher disp = new FXDIS.wfDispatcher();

    if (!string.IsNullOrEmpty(username))
    {
      //uid = disp.AuthenticateGateway(FXDIS.GatewayType.FileGateway, username);
      uid = FXapi.AuthenticateUser(username, pwd);
    }
    //else if (!string.IsNullOrEmpty(email))
   // {
      //uid = disp.AuthenticateGateway(FXDIS.GatewayType.Smtp, email); //FXapi.AuthenticateUser(username, pwd);
    //}

    logger.DebugLog("login id: " + uid.ToString());

    if (uid != 0 && uid != 1 && uid != 2)
    {
      Session["UID"] = uid;
      System.Collections.Generic.List<FXRecipient> recipients = new System.Collections.Generic.List<FXRecipient>();
      Session["recipients"] = recipients;
      Session["attachDocs"] = new System.Collections.Generic.List<AttachDoc>();
      Session["ftpIP"] = ConfigurationManager.AppSettings["FTPServerIP"].ToString();
      Session["ftpDir"] = ConfigurationManager.AppSettings["FTPLocalDir"].ToString();
      Session["ftpUN"] = ConfigurationManager.AppSettings["FTPUsername"].ToString();
      Session["ftpPWD"] = ConfigurationManager.AppSettings["FTPPass"].ToString();
      Session["fxIP"] = ConfigurationManager.AppSettings["FaxCoreIP"].ToString();
      bool exchangeEnable = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("EnableExchange"));

      Session["enEx"] = exchangeEnable;

      if (exchangeEnable)
      {
        Session["EX2007"] = ConfigurationManager.AppSettings["EX2007"].ToString();
        Session["ExchangeAddr"] = ConfigurationManager.AppSettings["ExchangeAddress"].ToString();
        Session["ExchangeFBA"] = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("ExchangeFBA"));
        Session["ExDomain"] = ConfigurationManager.AppSettings.Get("ExchangeDomain");
      }
      RetrieveUserInfo(uid.ToString(), Session["fxIP"].ToString());

      FXObject faxObj = new FXObject();
      faxObj.Username = hiddenUser.Value.Trim();  //txtUN.Text.Trim();
      faxObj.Password = hiddenPwd.Value.Trim(); //txtPwd.Text.Trim();
      Session["faxObj"] = faxObj;

      //string url = string.Format("fxMainMenu.aspx");
      //Response.Redirect(url);
    }
    else
    {
      //lblError.Text = "Login Failed";
      logger.SysLog("Login function"); ;
    }
    return uid;
  }

  private void RetrieveUserInfo(string uid, string server)
  {
    string query = String.Format(@"SELECT c.xDisplayName
      ,dbo.fxfn_User_Cfg_get(c.xUserID, N'COMPANY.NAME') AS xCompName 
      ,ISNULL(email.xDisplayAddress,N'') 
      ,ISNULL(fax.xDisplayAddress,N'')
      ,ISNULL(phone.xDisplayAddress,N'')
FROM dbo.fxtb_Contacts c
      LEFT JOIN dbo.fxtb_Contact_Addresses email ON (c.xContactID = email.xContactID AND email.xAddressTypeID = 1 AND email.xIsPrimary = 1)
      LEFT JOIN dbo.fxtb_Contact_Addresses fax ON (c.xContactID = fax.xContactID AND fax.xAddressTypeID = 2 AND fax.xIsPrimary = 1)
      LEFT JOIN dbo.fxtb_Contact_Addresses phone ON (c.xContactID = phone.xContactID AND phone.xAddressTypeID = 10 AND phone.xIsPrimary = 1)
WHERE c.xUserID = {0} AND c.xIsSelfContact = 1;", uid);

    string connStr = @"Data source=" + server + ";Initial Catalog=fxc;user id=fxc_admin;password=fxc_admin@pwd";

    System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query, conn);

    try
    {
      conn.Open();
      System.Data.IDataReader rdr = cmd.ExecuteReader();
      while (rdr.Read())
      {
        Sender user = new Sender();
        user.SenderPWD = hiddenPwd.Value.Trim();//txtPwd.Text.Trim();
        user.SenderUN = hiddenUser.Value.Trim();  //.Text.Trim();
        user.SenderCompany = rdr.GetString(1);
        user.SenderEmail = rdr.GetString(2);
        user.SenderFax = rdr.GetString(3);
        user.SenderName = rdr.GetString(0);
        user.SenderPhone = rdr.GetString(4);
        Session["sender"] = user;
      }
      conn.Close();
    }
    catch (Exception err)
    {
      logger.SysLog("Retrieve user info: " + err.Message);
    }
    finally
    {
      conn.Close();
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="hiddenUser" runat="server" Value="admin" />
    <asp:HiddenField ID="hiddenPwd" runat="server" Value="password" />
    <div>
    
    </div>
    </form>
</body>
</html>
