// Copyright (C) 2013 panacoran <panacoran@users.sourceforge.jp>
// Copyright (C) 2003 Daisuke Arai <darai@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: ProfitGraphBox.cs 466 2013-06-24 02:26:16Z panacoran $

using System;
using System.Drawing;
using System.Windows.Forms;
using Protra.Lib;

namespace PtSim.Controls
{
    /// <summary>
    /// 利益曲線を描くためのコントロール
    /// </summary>
    public class ProfitGraphBox : UserControl
    {
        private CumultiveProfitList _profitList;
        private Graphics _graphics;
        private readonly Color _marketColor = Color.Red;
        private readonly Color _bookColor = Color.Green;
        private float _labelHeight;
        private RectangleF _chartRectangle;
        private float _upperBound;
        private float _lowerBound;

        /// <summary>
        /// 描画する利益の集計値のリストを取得または設定する。
        /// </summary>
        public CumultiveProfitList ProfitList
        {
            get { return _profitList; }
            set
            {
                _profitList = value;
                Invalidate();
            }
        }

        /// <summary>
        /// Double Bufferingを有効にする。
        /// </summary>
        /// <param name="e">イベントの引数</param>
        protected override void OnLoad(EventArgs e)
        {
            DoubleBuffered = true;
        }

        /// <summary>
        /// ペイントイベントを処理する。
        /// </summary>
        /// <param name="e">イベントの引数</param>
        protected override void OnPaint(PaintEventArgs e)
        {
            if (ProfitList == null || ProfitList.Count < 2)
                return;
            _graphics = e.Graphics;
            _labelHeight = _graphics.MeasureString("1", Font).Height;
            _chartRectangle = new RectangleF(ClientRectangle.X, ClientRectangle.Y + _labelHeight,
                                             ClientRectangle.Width, ClientRectangle.Height - _labelHeight);
            DrawVirticalScale();
            DrawProfitLines();
            DrawLegends();
        }

        private void DrawVirticalScale()
        {
            var max = float.MinValue;
            var min = float.MaxValue;
            foreach (var profit in ProfitList)
            {
                max = Math.Max(max, Math.Max(profit.MarketProfit, profit.BookProfit));
                min = Math.Min(min, Math.Max(profit.MarketProfit, profit.BookProfit));
            }
            var ticks = (int)(_chartRectangle.Height / 40);
            if (ticks < 1)
                ticks = 1;
            var tickRange = TickRange(min, max, ticks);
            _upperBound = (float)(Math.Ceiling(max / tickRange) * tickRange);
            _lowerBound = (float)(Math.Floor(min / tickRange) * tickRange);
            var realTicks = (_upperBound - _lowerBound) / tickRange;
            var tick = _lowerBound;
            var y = _chartRectangle.Bottom;
            var tickSize = _chartRectangle.Height / realTicks;
            while (FloatComparers.Compare(tick, _upperBound) <= 0)
            {
                _graphics.DrawLine(new Pen(Color.FromArgb(0x80, Color.Gray)),
                                   _chartRectangle.Left, y, _chartRectangle.Right, y);
                _graphics.DrawString(tick.ToString("C"), Font, new SolidBrush(ForeColor),
                                     _chartRectangle.Left, y - _labelHeight);
                tick += tickRange;
                y -= tickSize;
            }
        }

        private static float TickRange(float min, float max, int ticks)
        {
// ReSharper disable CompareOfFloatsByEqualityOperator
            var range = (max != min) ? max - min : 1f;
// ReSharper restore CompareOfFloatsByEqualityOperator
            var raw = range / ticks;
            var base10 = Math.Floor(Math.Log10(raw));
            var power10 = Math.Pow(10, base10);
            var topdigit = Math.Ceiling(raw / power10);
            return (float)(topdigit * power10);
        }

        private void DrawProfitLines()
        {
            var xscale = (_chartRectangle.Width - 2) / ProfitList.Count; // 一番右まで描くとわかりにくいので2px空ける。
            var yscale = _chartRectangle.Height / (_upperBound - _lowerBound);
            var marketPrevPoint = new PointF();
            var bookPrevPoint = new PointF();
            for (var i = 0; i < ProfitList.Count; i++)
            {
                var profit = ProfitList[i];
                var marketPoint = new PointF(xscale * i,
                                             yscale * (_upperBound - profit.MarketProfit) + _chartRectangle.Top);
                var bookPoint = new PointF(xscale * i, yscale * (_upperBound - profit.BookProfit) + _chartRectangle.Top);
                if (i > 0)
                {
                    _graphics.DrawLine(new Pen(_marketColor), marketPrevPoint, marketPoint);
                    _graphics.DrawLine(new Pen(_bookColor), bookPrevPoint, bookPoint);
                }
                marketPrevPoint = marketPoint;
                bookPrevPoint = bookPoint;
            }
        }

        private void DrawLegends()
        {
            var label = "時価";
            var size = _graphics.MeasureString(label, Font);
            var rectangle = new RectangleF(_chartRectangle.Right - size.Width - 10,
                                           _chartRectangle.Bottom - size.Height - 10,
                                           size.Height, size.Height);
            _graphics.FillRectangle(new SolidBrush(_marketColor), rectangle);
            _graphics.DrawRectangles(new Pen(ForeColor), new[] {rectangle});
            _graphics.DrawString(label, Font, new SolidBrush(ForeColor), rectangle.Right, rectangle.Top);
            label = "簿価";
            size = _graphics.MeasureString(label, Font);
            rectangle.X -= size.Width + size.Height;
            _graphics.FillRectangle(new SolidBrush(_bookColor), rectangle);
            _graphics.DrawRectangles(new Pen(ForeColor), new[] {rectangle});
            _graphics.DrawString(label, Font, new SolidBrush(ForeColor), rectangle.Right, rectangle.Top);
        }
    }
}