//
// MainWindow.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013 
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Gtk;
using Ntp.Analyzer.Gui;
using Ntp.Analyzer.Gui.Control;
using Ntp.Analyzer.Gui.Model;
using Ntp.Analyzer.Graph;
using Gdk;
using Ntp.Analyzer.Data;
using System.Linq;
using System.IO;

namespace Ntp.Analyzer.Gui.Window
{
    public partial class MainWindow: Gtk.Window
    {	
        #region Initialization
        public MainWindow (MainWindowController controller): base (Gtk.WindowType.Toplevel)
        {
            this.controller = controller;

            Build ();

            tag = new TextTag ("font");
            tag.Font = "Courier 10";
            textview2.Buffer.TagTable.Add (tag);

            headingTag = new TextTag ("bold");
            headingTag.Font = "Courier 11";
            headingTag.Weight = Pango.Weight.Bold;
            textview2.Buffer.TagTable.Add (headingTag);

            drawingarea1.Visible = false;
        }

        private readonly MainWindowController controller;
        private readonly TextTag headingTag;
        private readonly TextTag tag;
        #endregion
        #region UI Logic
        public void Clear ()
        {
            scrolledwindow1.Visible = true;
            drawingarea1.Visible = false;
            textview2.Buffer.Text = String.Empty;
        }

        public void ShowResult (string heading, string text)
        {
            TextIter end = textview2.Buffer.EndIter;

            textview2.Buffer.InsertWithTags (ref end, heading, headingTag);
            textview2.Buffer.InsertWithTags (ref end, Environment.NewLine, headingTag);
            textview2.Buffer.InsertWithTags (ref end, text, tag);
            textview2.Buffer.InsertWithTags (ref end, Environment.NewLine, tag);
            textview2.Buffer.InsertWithTags (ref end, Environment.NewLine, tag);
        }

        private Pixbuf mapContents;
        #endregion
        #region Event Handlers
        protected void TextviewKeyRelease (object o, KeyReleaseEventArgs args)
        {
            if (args.Event.Key == Gdk.Key.Return) {
                string command = textview2.Buffer.Text;
                controller.ExecuteCommand (command);
            }
        }

        protected void OnHomeActionActivated (object sender, EventArgs e)
        {
            controller.HomeSelected ();
        }

        protected void NetworkClicked (object sender, EventArgs e)
        {
            controller.NetworkSelected ();
        }

        protected void CommandClicked (object sender, EventArgs e)
        {
            controller.SelectCommand ();
        }

        protected void CloseClicked (object sender, DeleteEventArgs a)
        {
            Application.Quit ();
            a.RetVal = true;
        }

        protected void OnExecuteActionActivated (object sender, EventArgs e)
        {
            Ntp.Analyzer.Objects.Host ho =
                DataFace.Instance.Hosts.Single (h => h.Id == 1);

            scrolledwindow1.Visible = false;
            drawingarea1.Visible = true;

            table1.QueueResize ();
            Application.RunIteration ();

            int width;
            int height;

            drawingarea1.GdkWindow.GetSize (out width, out height);

            s = new TrafficGraphSettings ();
            s.Width = width;
            s.Height = height;
            s.Title = "Helloe";
            s.Timespan = 3;
            s.Received = 1;
            s.ReceivedAvg = 1;
            s.PacketRate = 1;
            s.PlotInterval = 15;
            s.HostId = ho.Id;

            graph = new TrafficGraph (s, ho);
            Stream str = graph.Generate ();
            str.Position = 0;
            mapContents = new Gdk.Pixbuf (str);
        }

        protected void OnDrawingarea1ExposeEvent (object o, ExposeEventArgs args)
        {   
            Gdk.Rectangle area = args.Event.Area;

            int width = area.Width > mapContents.Width ? mapContents.Width : area.Width;
            int height = area.Height > mapContents.Height ? mapContents.Height : area.Height;

            Gdk.GC gc = drawingarea1.Style.BlackGC;
            drawingarea1.GdkWindow.Background = new Color (0, 0, 0);
            drawingarea1.GdkWindow.DrawPixbuf (gc,
                                               mapContents,
                                               area.X, area.Y,
                                               area.X, area.Y,
                                               width, height,
                                               RgbDither.Normal,
                                               width, height);


            args.RetVal = true;
        }

        private TrafficGraphSettings s;
        private TrafficGraph graph;

        protected void OnDrawingarea1SizeAllocated (object o, SizeAllocatedArgs args)
        {
            if (graph == null)
                return;

            int width;
            int height;

            drawingarea1.GdkWindow.GetSize (out width, out height);

            s.Height = height;
            s.Width = width;

            Stream str = graph.Render ();
            str.Position = 0;
            mapContents = new Gdk.Pixbuf (str);
        }

        #endregion
    }
}
