using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;

/// <summary>
/// Summary description for LogWriter
/// </summary>
public class LogWriter
{
    private const long _logFileSize = 10 * 1024 * 1024;      // 10MB
    private static Object _lock = new Object();
    private StringBuilder _log = new StringBuilder();
    private string _logFolder = "";
    private bool _useLogWriter = false;

    public LogWriter()
    {
    }

    public LogWriter(HttpRequest request)
    {
        _useLogWriter = AppSetting.UseLogWriter;
        SetRequest(request);
    }

    public void SetRequest(HttpRequest request)
    {
        if (_useLogWriter)
        {
            _log.Append(DateTime.Now.ToLongTimeString() + "\r\n");
            _log.Append(string.Format("{0} {1}\r\n", WebUser.CurrentUser.MailAddress, request.UserHostAddress));
            _log.Append(string.Format("{0} {1}\r\nReferer: {2}\r\nAgent: {3}\r\n",
                request.HttpMethod, request.RawUrl, request.UrlReferrer, request.UserAgent));
            _logFolder = request.MapPath("~/App_Data");
        }
    }

    public void AddLog(string log)
    {
        if (_useLogWriter) _log.Append(log);
    }

    public void AddLogLine(string log)
    {
        if (_useLogWriter)
        {
            _log.Append(log);
            _log.Append("\r\n");
        }
    }

    public void AddForm(HttpRequest request, string key)
    {
        if (_useLogWriter)
        {
            string[] keys = request.Form.AllKeys;
            if (keys.Length > 0)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    if (i > 0) _log.Append(", ");
                    _log.Append(keys[i]);
                    if (keys[i] == key) _log.Append(string.Format(":{0}", request.Form[i]));
                }
            }
            else
            {
                _log.Append("No form values");
            }
            _log.Append("\r\n");
        }
    }

    public void AddException(Exception ex)
    {
        if (_useLogWriter)
            _log.Append(string.Format("Exception: {0}\r\n\t{1}\r\n\t{2}\r\n", ex.Source, ex.Message, ex.StackTrace));
    }

    public void Write()
    {
        lock (_lock)
        {
            if (_useLogWriter)
            {
                string logFile = string.Format("{0}\\Info.log", _logFolder);
                FileInfo fi = new FileInfo(logFile);
                if (fi.Exists && fi.Length > _logFileSize)
                {
                    int no = 1;
                    bool exist = true;
                    string oldLogFile = "";
                    while (exist)
                    {
                        oldLogFile = string.Format("{0}\\Info-{1:D4}.log", _logFolder, no++);
                        exist = File.Exists(oldLogFile);
                    }
                    try
                    {
                        File.Move(logFile, oldLogFile);
                    }
                    catch { }
                }
                
                using (StreamWriter file = new StreamWriter(logFile, true, System.Text.Encoding.UTF8))
                {
                    _log.Append("\r\n");
                    file.Write(_log.ToString());
                    _log.Clear();
                }
            }
        }
    }
}