using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Web;
using System.Diagnostics;
using pcmp.Setting;

namespace pcmp
{
    public static class Common
    {
        // ----------------------------------------------------------
        // 置換用パターン定数
        // ----------------------------------------------------------
        // タグ public const string PatternA = "(?i:<aaa[ \t]*/>)";
        public const string PatternDiff = "(?i:<(rank|diff)[ \t]*/>)";
        public const string PatternNo = "(?i:<(no|num)[ \t]*/>)";
        public const string PatternChannelName = "(?i:<channelname[ \t]*/>)";
        public const string PatternDescription = "(?i:<description[ \t]*/>)";
        public const string PatternListener = "(?i:<(listener|status)[ \t]*/>)";
        public const string PatternBitrate = "(?i:<bitrate[ \t]*/>)";
        public const string PatternType = "(?i:<type[ \t]*/>)";
        public const string PatternContactURL = "(?i:<(contact|contacturl)[ \t]*/>)";
        public const string PatternStreamURL = "(?i:<(stream|streamurl)[ \t]*/>)";
        public const string PatternDirectStreamURL = "(?i:<(directstream|directstreamurl)[ \t]*/>)";
        public const string PatternChatURL = "(?i:<chat[ \t]*/>)";
        public const string PatternStatisticsURL = "(?i:<(statistics|gmt)[ \t]*/>)";
        public const string PatternHash = "(?i:<(hash|id)[ \t]*/>)";
        public const string PatternPlaying = "(?i:<playing[ \t]*/>)";
        public const string PatternYpAddr = "(?i:<ypaddr[ \t]*/>)";
        public const string PatternYpName = "(?i:<ypname[ \t]*/>)";
        public const string PatternComment = "(?i:<comment[ \t]*/>)";
        public const string PatternAlt = "(?i:<(kyasukostatus|alt)[ \t]*/>)";
        public const string PatternBroadCastTime = "(?i:<broadcasttime[ \t]*/>)";
        public const string PatternForeColor = "(?i:<forecolor[ \t]*/>)";
        public const string PatternBackColor = "(?i:<backcolor[ \t]/>)";
        // フッター・ヘッダーで使用可能
        public const string PatternTimeStamp = "(?i:<(timestamp|gettime)[ \t]*/>)";
        public const string PatternTemplatePath = "(?i:<templatePath[ \t]*/>)";
        public const string PatternTemplatePathd = "(?i:<templatePath_d[ \t]*/>)";
        public const string PatternTemplatePaths = "(?i:<templatePath_s[ \t]*/>)";
        // フッター・ヘッダーのみ
        public const string PatternTotalResult = "(?i:<total(result|count)[ \t]*/>)";
        public const string PatternCurrentResult = "(?i:<currentresult[ \t]*/>)";
        public const string PatternCurrentYP = "(?i:<currentyp[ \t]*/>)";
        public const string PatternShowScriptError = "(?i:<showscripterror[ \t]*/>)";
        public const string PatternYPArray = "(?i:<yparray[ \t]*/>)";

        // ----------------------------------------------------------
        // 定数
        // ----------------------------------------------------------
        public const string CommandActivate = "ACTIVATEWINDOW";
        public const string WindowName = "PeerCastMultiPlayer2";

        public static string ReplaceHtml(string html, Channel item, string template)
        {
            if (item == null) return string.Empty;
            html = ReplaceTag(html, item);

            string path;
            if (template != string.Empty)
                path = template;
            else
                path = Path.Combine(Application.StartupPath, "templates\\default\\");
            if (!path.EndsWith("\\")) path += "\\";
            html = Regex.Replace(html, PatternTemplatePath, path);

            // \ を / に置き換える
            path = path.Replace("\\", "/");
            html = Regex.Replace(html, PatternTemplatePaths, path);

            // / を \\ に置き換える
            path = path.Replace("/", "\\\\");
            html = Regex.Replace(html, PatternTemplatePathd, path);

            return html;
        }

        public static string ReplaceTag(string text, Channel item)
        {
            string diff = string.Empty;
            switch (item.Diff)
            {
                case ChannelDiff.New:
                    diff = "新着";
                    break;
                case ChannelDiff.Up:
                    diff = "ランクアップ";
                    break;
                case ChannelDiff.Down:
                    diff = "ランクダウン";
                    break;
                case ChannelDiff.None:
                    diff = "変化なし";
                    break;
            }
            text = Regex.Replace(text, PatternDiff, diff);
            text = Regex.Replace(text, PatternNo, item.No.ToString());
            text = Regex.Replace(text, PatternChannelName, item.ChannelName);
            text = Regex.Replace(text, PatternDescription, item.Desc);
            text = Regex.Replace(text, PatternListener, item.Status.ToString());
            text = Regex.Replace(text, PatternBitrate, item.BitRate.ToString());
            text = Regex.Replace(text, PatternType, item.Type);
            text = Regex.Replace(text, PatternTimeStamp, item.GetTime);
            text = Regex.Replace(text, PatternContactURL, item.ContactUrl);
            text = Regex.Replace(text, PatternStreamURL, item.StreamUrl);
            text = Regex.Replace(text, PatternDirectStreamURL, item.DirectStreamUrl);
            text = Regex.Replace(text, PatternChatURL, item.ChatUrl);
            text = Regex.Replace(text, PatternStatisticsURL, item.StatUrl);
            text = Regex.Replace(text, PatternHash, item.ID);
            text = Regex.Replace(text, PatternPlaying, item.Playing);
            text = Regex.Replace(text, PatternYpAddr, item.YPUrl);
            text = Regex.Replace(text, PatternYpName, item.YPName);
            text = Regex.Replace(text, PatternComment, item.Comment);
            text = Regex.Replace(text, PatternAlt, item.Alt);
            text = Regex.Replace(text, PatternBroadCastTime, item.Time.ToString());

            return text;
        }

        public static string ReplaceTag(string text, YpSetting yp)
        {
            text = Regex.Replace(text, PatternYpAddr, yp.YpAddr);

            return text;
        }

        /// <summary>
        /// HTMLEncodeする
        /// </summary>
        /// <param name="text">エンコードする文字列</param>
        /// <returns>エンコードされた文字列</returns>
        public static string Enc(string text)
        {
            return EncodeYenMark(HttpUtility.HtmlEncode(text));
        }

        public static string EncodeYenMark(string text)
        {
            return text.Replace("\\", "&yen;");
        }

        public static string ToColorCode(Color color)
        {
            string code = string.Format("#{0}{1}{2}",
                color.R.ToString("X2"), color.G.ToString("X2"), color.B.ToString("X2"));
            return code;
        }

        /// <summary>
        /// 文字列の両端に"を付ける
        /// </summary>
        /// <param name="arg">"を付ける文字列</param>
        /// <returns>"が付けられた文字列</returns>
        public static string AddQuot(string arg)
        {
            return "\"" + arg + "\"";
        }

        public static string CreatePeercastUrl(string url)
        {
            // http://localhost:7144/pls/661E101A1A0E2C0F4FC4B8A291CBE992?tip=124.102.58.175:7144
            // peercast://pls/661E101A1A0E2C0F4FC4B8A291CBE992?tip=124.102.58.175:7144
            string ret = Regex.Replace(url, "http://[^:]+:[1-9]+/", "peercast://");
            return ret;
        }

        /// <summary>
        /// WorkingDirectryを設定してProcessを起動する
        /// </summary>
        /// <param name="fileName">起動するファイル</param>
        /// <param name="arg">引数</param>
        public static void StartProcess(string fileName, string arg)
        {
            if (string.IsNullOrEmpty(fileName)) return;

            Process p = new Process();
            p.StartInfo.FileName = fileName;
            if (!string.IsNullOrEmpty(arg))
                p.StartInfo.Arguments = arg;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileName);
            try
            {
                p.Start();
            }
            catch (Exception ex) { Trace.WriteLine(ex.Message + " " + fileName); }

            p.Dispose();
        }

        public static void StartConime()
        {
            //
            // Original: http://mho.s1.xrea.com/archives/2005/12/post_233.html
            //

            Process p = new Process();
            try
            {
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.Arguments = "/C conime.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
            }
            finally
            {
                if (p != null)
                    p.Close();
            }
        }
    }
}
