using System;
using System.Collections;
using System.IO;
using Server;
using Server.Gumps;
using Server.Mobiles;
using Knives.Utils;

namespace Knives.Chat3
{
    public class General
    {
        private static string s_Version = "3.0 Beta 6";
        private static DateTime s_ReleaseDate = new DateTime(2006, 6, 18);

        public static string Version { get { return s_Version; } }
        public static DateTime ReleaseDate { get { return s_ReleaseDate; } }

        private static ArrayList s_Locals = new ArrayList();

        public static void Configure()
        {
            EventSink.WorldLoad += new WorldLoadEventHandler(OnLoad);
            EventSink.WorldSave += new WorldSaveEventHandler(OnSave);
        }

        public static void Initialize()
        {
            EventSink.Speech += new SpeechEventHandler(OnSpeech);
            EventSink.Login += new LoginEventHandler(OnLogin);
            EventSink.CharacterCreated += new CharacterCreatedEventHandler(OnCreate);
        }

        private static void OnLoad()
        {
            LoadLocalFile();

            try
            {
                Data.Load();
            }
            catch
            {
                Errors.Report(Local(174));
            }

            try
            {
                Channel.Load();
            }
            catch
            {
                Errors.Report(Local(186));
            }

            if (Data.IrcAutoConnect)
                IrcConnection.Connection.Connect();
        }

        private static void OnSave(WorldSaveEventArgs args)
        {
            try
            {
                Data.Save();
            }
            catch
            {
                Errors.Report(Local(175));
            }

            try
            {
                Channel.Save();
            }
            catch
            {
                Errors.Report(Local(187));
            }
        }

        private static void OnSpeech(SpeechEventArgs args)
        {
            if (Data.GetData(args.Mobile).Recording is SendMessageGump)
            {
                if (!args.Mobile.HasGump(typeof(SendMessageGump)))
                {
                    Data.GetData(args.Mobile).Recording = null;
                    return;
                }

                ((SendMessageGump)Data.GetData(args.Mobile).Recording).AddText(" " + args.Speech);
                args.Handled = true;
                args.Speech = "";
                return;
            }

            if (Data.GetData(args.Mobile).FriendsSpeech == args.Speech)
            {
                FriendsGump.SendTo(args.Mobile);
                args.Handled = true;
                args.Speech = "";
                return;
            }

            if (Data.GetData(args.Mobile).ChannelsSpeech == args.Speech)
            {
                ChannelGump.SendTo(args.Mobile);
                args.Handled = true;
                args.Speech = "";
                return;
            }
     
            if (Data.GetData(args.Mobile).MailSpeech == args.Speech)
            {
                MailGump.SendTo(args.Mobile);
                args.Handled = true;
                args.Speech = "";
                return;
            }

            if (Data.FilterSpeech)
                args.Speech = Filter.FilterText(args.Mobile, args.Speech, false);

            foreach (Data data in Data.Datas.Values)
                if (data.Mobile.AccessLevel >= args.Mobile.AccessLevel && ((data.GlobalW && !data.GIgnores.Contains(args.Mobile)) || data.GListens.Contains(args.Mobile)) && !data.Mobile.InRange(args.Mobile.Location, 10))
                    data.Mobile.SendMessage(data.GlobalWC, String.Format("(Global) <World> {0}: {1}", args.Mobile.Name, args.Speech));
        }

        private static void OnLogin(LoginEventArgs args)
        {
            foreach (Data data in Data.Datas.Values)
            {
                if (data.Friends.Contains(args.Mobile) && data.FriendAlert)
                    data.Mobile.SendMessage(data.SystemC, args.Mobile.Name + " " + Local(173));

                if (data.SevenDays)
                    foreach (Message msg in new ArrayList(data.Messages))
                        if (msg.Received < DateTime.Now - TimeSpan.FromDays(7))
                            data.Messages.Remove(msg);
            }
        }

        private static void OnCreate(CharacterCreatedEventArgs args)
        {
            if (args.Mobile == null)
                return;

            Data data = Data.GetData(args.Mobile);

            foreach (Channel c in Channel.Channels)
                if (c.NewChars)
                    data.Channels.Add(c.Name);
        }

        public static void LoadLocalFile()
        {
            s_Locals.Clear();

            if (File.Exists("Data/ChatLocal.txt"))
            {
                using (FileStream bin = new FileStream("Data/ChatLocal.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    StreamReader reader = new StreamReader(bin);
                    string text = "";

                    while (true)
                    {
                        try
                        {
                            text = reader.ReadLine();

                            if (text == "EndOfFile")
                                break;

                            s_Locals.Add(text);
                        }
                        catch { break; }
                    }

                    reader.Close();
                }
            }

            if (s_Locals.Count == 0)
                s_Locals = DefaultLocal.Load();
        }

        public static string Local(int num)
        {
            if (num < 0 || num >= s_Locals.Count)
                return "Local Error";

            return s_Locals[num].ToString();
        }

        public static void RefreshGump(Mobile m, Type type)
        {
            if (m.NetState == null)
                return;

            foreach (Gump g in m.NetState.Gumps)
                if (g is GumpPlus && g.GetType() == type)
                {
                    m.CloseGump(type);
                    ((GumpPlus)g).NewGump();
                    return;
                }
        }

        public static void ClearGump(Mobile m, Type type)
        {
            if (m.NetState == null)
                return;

            m.CloseGump(type);

            foreach (Gump g in new ArrayList(m.NetState.Gumps))
                if (g.GetType() == type)
                {
                    m.NetState.Gumps.Remove(g);
                    return;
                }
        }
        
        public static bool IsInFaction(Mobile m)
        {
            if (m == null || !m.Player)
                return false;

            return (((PlayerMobile)m).FactionPlayerState != null && ((PlayerMobile)m).FactionPlayerState.Faction != null);
        }

        public static string FactionName(Mobile m)
        {
            if (!IsInFaction(m))
                return "";

            return ((PlayerMobile)m).FactionPlayerState.Faction.Definition.PropName;
        }

        public static string FactionTitle(Mobile m)
        {
            if (!IsInFaction(m))
                return "";

            return ((PlayerMobile)m).FactionPlayerState.Rank.Title;
        }
    }
}