
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using nft.framework.drawing;
using nft.core.game;
using nft.impl.game;
using nft.core.geometry;
using Geocon = nft.core.geometry.GeometricConstants;
using ITerrainPiece = nft.core.geometry.ITerrainPiece;
using nft.framework;
using nft.core;
using System.Diagnostics;
using System.Windows.Forms;

namespace nft.impl.view_old {
    /// <summary>
    /// 旧MapViewDrawer 新Drawer完成までの代替
    /// </summary>
    public class TerrainDrawer : ViewDrawerBase, IQuarterView {
        TerrainMapImpl map;
        ViewFactor factor;
        QVSpriteTree sprTree = new QVSpriteTree();

        public TerrainDrawer(ITerrainMap srcmap) {
            if (!(srcmap is TerrainMapImpl)) {
                map = new TerrainMapImpl(srcmap);
            } else {
                map = srcmap as TerrainMapImpl;
            }
            factor = new ViewFactor(InterCardinalDirection.NORTHEAST);
        }

        #region IQuarterView implementation
        public ViewFactor ViewFactor {
            get {
                return factor.Clone();
            }
            set {
                if (factor.Equals(value)) {
                    bool b = (value.Scale != factor.Scale || value.ViewDirection != factor.ViewDirection);
                    Size szold = ContentSize;
                    ViewFactor vwold = factor;
                    factor = value.Clone();
                    if (b) {
                        NotifyContentSizeChanged(vwold, szold);
                    } else {
                        NotifyAllUpdated(false);
                    }
                }
            }
        }

        public Control TargetControl {
            get { throw new NotImplementedException(); }
        }

        public Location GetHitSprite(IView v, Point pt, out object tag) {
            throw new NotImplementedException();
        }

        public Location ConvertMousePos(IView v, Point pt) {
            throw new NotImplementedException();
        }

        public Location ConvertMousePos(IView v, Point pt, int height) {
            throw new NotImplementedException();
        }

        public LocationF ConvertMousePosF(IView v, Point pt) {
            throw new NotImplementedException();
        }

        public LocationF ConvertMousePosF(IView v, Point pt, int height) {
            throw new NotImplementedException();
        }
        #endregion

        protected virtual void NotifyContentSizeChanged(ViewFactor oldVF, Size oldSize) {
            double v = ViewFactor.Scaler.Value / oldVF.Scaler.Value;
            // TODO: consider rotation
            foreach (IView vw in views) {
                Rectangle rectPrv = vw.VisibleSourceRect;
                int wo = rectPrv.Width >> 1;
                int ho = rectPrv.Height >> 1;
                Point pos = rectPrv.Location;
                pos.Offset(wo,ho);
                pos.X = (int)(pos.X * v);
                pos.Y = (int)(pos.Y * v);
                pos.Offset(-wo, -ho);
                vw.NotifyContentSizeChanged(pos);
            }
        }

        protected virtual Location ViewToMap(ViewFactor factor, Point pt, int Z) {
            throw new NotImplementedException();
        }

        #region IViewDrawer implementation
        protected override void DrawCore(ISurfaceOld surfDest, Graphics g, IView owner, Rectangle rctDest, Region requestSrc) {
            int t1 = System.Environment.TickCount;
            int t2;
            surfDest.Clear(rctDest, Color.Navy);
            Rectangle rectReq = Rectangle.Round(requestSrc.GetBounds(g));
            Scaler scl = ViewFactor.Scaler;
            Size3D szmap = map.Size;
            sprTree.Clear(false);
            Point offset = rctDest.Location;
            Point vp = owner.ViewPosition;
            offset.Offset(-vp.X, -vp.Y);
            DrawParams param = new DrawParams(surfDest, offset);
            using (TreeBuilder builder = new TreeBuilder(this, owner, rectReq)) {
                t2 = System.Environment.TickCount;
                t1 = t2 - t1;
                foreach (TreeElement elm in sprTree.Root.GetBottomUpEnumerator()) {                    
                    ISprite sprite = elm.Sprite;
                    if (sprite != null) {
                        sprite.Draw(param);
                    }
                }
            }
            t2 = System.Environment.TickCount - t2;
#if DEBUG
            Debug.WriteLine("Draw ticks=" + t1 + "/" + t2 + ": dest=" + rctDest);
#else
            Console.WriteLine("Draw ticks=" + t1 + "/" + t2 + ": dest=" + rctDest);
#endif
        }

        internal protected TerrainMapImpl TerrainMap { get { return map; } }

        public Size3D WorldSize {
            get { return map.Size; }
        }

        public override Size ContentSize {
            get {
                int x = map.Size.sx*Geocon.CellWidthPixel;
                int y = map.Size.sy*Geocon.CellWidthPixel;
                int w = x + y;
                int h = (w >> 1) + map.Size.sz * Geocon.CellHeightPixel * Geocon.TerrainHeightStep;
                Size sz = new Size(w, h);
                factor.Scaler.Scale(ref sz);
                return sz;
            }
        }

        public override Size ScrollUnit {
            get {
                int u = Geocon.CellWidthPixel;
                Size sz = new Size(u, u >> 1);
                factor.Scaler.Scale(ref sz);
                return sz;
            }
        }
        #endregion
        /*
        protected void ProcessBehindCells(Location l, Rectangle destArea) {

        }
        */
        protected class TreeBuilder : IDisposable{
            TerrainDrawer mvDrawer;
            Rectangle rectRequested;
            Scaler scaler;
            Size3D szMap;
            QVCellSelector qvSelector;
            InterCardinalDirection upperDir;
            int unitWidth;
            int unitHeight;
            int[] work;

            public TreeBuilder(TerrainDrawer drawer, IView owner, Rectangle requestArea) {
                this.mvDrawer = drawer;
                this.rectRequested = requestArea;
                this.scaler = drawer.ViewFactor.Scaler;
                this.szMap = drawer.map.Size;
                this.qvSelector = QVCellSelector.GetSelector(drawer.ViewFactor.ViewDirection);
                this.unitWidth = scaler.Scale(Geocon.CellWidthPixel);
                this.unitHeight = scaler.Scale(Geocon.CellHeightPixel)>>1;
                //rectRequested.Width += unitWidth;
                this.upperDir = mvDrawer.ViewFactor.ViewDirection;
                // because we must draw cells on left and right border too,
                // we need to assign some more (=4) elements for work array.
                this.work = new int[rectRequested.Width / unitWidth + 4];
                foreach (Location l in qvSelector.GetBottomCells(requestArea, mvDrawer)) {
                    Process(l, mvDrawer.sprTree.Root);
                }
            }

            protected void Process(Location l,TreeElement elm) {
                Rectangle bounds = qvSelector.GetQVBoundsOfCell(mvDrawer, l);
                //if (rectRequested.IntersectsWith(bounds)) {
                int h = rectRequested.Bottom - bounds.Bottom;
                int i0 = Math.Max(0,(bounds.Right - rectRequested.Left) / unitWidth);
                if (i0 >= work.Length) return;
                ProcData data = new ProcData(l);
                Point3DV p3dv = new Point3DV();
                // TODO 位置合わせ適当・Cliffなし
                #region foreach (ITerrainPiece)
                foreach (ITerrainPiece tp in mvDrawer.TerrainMap[l.X, l.Y, upperDir]) {
                    int th = tp.BaseHeight * unitHeight;
                    int h2 = h + th;
                    int i = i0;                        
                    data.tpSet = tp.Template.GetPolygons(upperDir);
                    data.drawPos = bounds.Location;
                    data.drawPos.Y -= th;
                    Rectangle tmp = data.tpSet.Ground.GetBounds(scaler);
                    if (data.tpSet.HorzSplitted) {
                        if (tmp.Bottom == 0) {
                            data.hgap = h2 - work[i];
                            if (0 <= data.hgap) {
                                elm = ProcessLeftCliff(elm, data);
                                work[i] = h2 - bounds.Height;
                                if (++i < work.Length && 0 <= (data.hgap = h2 - work[i])) {
                                    elm = ProcessRightCliff(elm, data);
                                    work[i] = h2 - bounds.Height;
                                }
                                elm = CreateSprite(data.tpSet.Ground, data.drawPos, p3dv, elm);
                            } else if (++i < work.Length && 0 <= (data.hgap = h2 - work[i])) {
                                elm = ProcessRightCliff(elm, data);
                                work[i] = h2 - bounds.Height;
                                elm = CreateSprite(data.tpSet.Ground, data.drawPos, p3dv, elm);
                            }
                        } else {
                            data.hgap = h2 - work[i];
                            if (0 <= data.hgap) {
                                work[i] = h2 - bounds.Height;
                            }
                            int d;
                            if (++i < work.Length && 0 <= (d = h2 - work[i])) {
                                data.hgap = Math.Max(data.hgap, d);
                                work[i] = h2 - bounds.Height;
                            }
                            if (0 <= data.hgap) {
                                elm = ProcessDiagonalCliff(elm, data);
                                elm = CreateSprite(data.tpSet.Ground, data.drawPos, p3dv, elm);
                            }
                        }
                    } else {
                        if ( tmp.X < 0) {
                            data.hgap = h2 - work[i];
                            if (0 <= data.hgap) {
                                elm = ProcessLeftCliff(elm, data);
                                work[i] = h2 - bounds.Height;
                                elm = CreateSprite(data.tpSet.Ground, data.drawPos, p3dv, elm);
                            }
                        } else {
                            if (++i < work.Length && 0 <= (data.hgap = h2 - work[i])) {
                                elm = ProcessRightCliff(elm, data);
                                work[i] = h2 - bounds.Height;
                                elm = CreateSprite(data.tpSet.Ground, data.drawPos, p3dv, elm);
                            }
                        }
                    }
                }
                #endregion                    
                if(bounds.Bottom>rectRequested.Top && bounds.Right>rectRequested.Left ) {
                    if (qvSelector.MoveToUpperLeftCell(ref l, szMap)) {
                        Process(l, elm);
                    }
                }                    
                //}
            }

            protected TreeElement ProcessDiagonalCliff(TreeElement elm, ProcData data) {
                if (qvSelector.IsDiagonalCliffVisible(mvDrawer.TerrainMap, data.cellLoc)!=0) {
                    Point pt = new Point(data.drawPos.X, data.drawPos.Y);
                    Point3DV hint = new Point3DV();
                    if (data.tpSet.CliffDiagonal != null) {
                        elm = CreateSprite(data.tpSet.CliffDiagonal, pt, hint, elm);
                    }
                    while (data.hgap > 0) {
                        int h = Geocon.TerrainHeightMax * unitHeight;
                        pt.Y += h;
                        elm = CreateSprite(CliffPolygon.GetPolygon(0x8f8f), pt, hint, elm);
                        data.hgap -= h;
                    }
                }
                return elm;
            }

            protected TreeElement ProcessLeftCliff(TreeElement elm, ProcData data) {
                if (qvSelector.IsLeftCliffVisible(mvDrawer.TerrainMap, data.cellLoc)) {
                    Point pt = new Point(data.drawPos.X, data.drawPos.Y);
                    Point3DV hint = new Point3DV();
                    if (data.tpSet.CliffLeft != null) {
                        elm = CreateSprite(data.tpSet.CliffLeft, pt, hint, elm);
                    }
                    while (data.hgap > 0) {
                        int h = Geocon.TerrainHeightMax * unitHeight;
                        pt.Y += h;
                        elm = CreateSprite(CliffPolygon.GetPolygon(0x8ff8), pt, hint, elm);
                        data.hgap -= h;
                    }
                }
                return elm;
            }

            protected TreeElement ProcessRightCliff(TreeElement elm, ProcData data) {
                if (qvSelector.IsRightCliffVisible(mvDrawer.TerrainMap, data.cellLoc)) {
                    Point pt = new Point(data.drawPos.X, data.drawPos.Y);
                    Point3DV hint = new Point3DV();
                    if (data.tpSet.CliffRight != null) {
                        elm = CreateSprite(data.tpSet.CliffRight, pt, hint, elm);
                    }
                    while (data.hgap > 0) {
                        int h = Geocon.TerrainHeightMax * unitHeight;
                        pt.Y += h;
                        elm = CreateSprite(CliffPolygon.GetPolygon(0xff88), pt, hint, elm);
                        data.hgap -= h;
                    }
                }
                return elm;
            }

            protected TreeElement CreateSprite(GroundPolygon poly, Point pt, Point3DV hint, TreeElement elm) {
                if(poly.IsVisible){
                    IApparentAssignor asignor = DefaultApparentAssignor.TheInstance;
                    IGraphicManagerOld gm = GlobalModules.GraphicManagerOld;
                    ITextureOld tx = asignor.DefaultLandTexture.GetTexture(scaler, poly, hint);
                    ISprite sp = gm.CreateSprite(tx);
                    sp.Location = pt;                    
                    return elm.AddChild(sp, 0);

                } else {
#if DEBUG
                    //Debug.WriteLine("Sprite invisible for id="+poly.ID.ToString("X4")+" at Point("+pt.X+","+pt.Y+").");
#endif
                    return elm;
                }
            }

            protected TreeElement CreateSprite(CliffPolygon poly, Point pt, Point3DV hint, TreeElement elm) {
                IApparentAssignor asignor = DefaultApparentAssignor.TheInstance;
                IGraphicManagerOld gm = GlobalModules.GraphicManagerOld;
                ITextureOld tx = asignor.DefaultCliffTexture.GetTexture(scaler, poly, hint);
                ISprite sp = gm.CreateSprite(tx);
                sp.Location = pt;
                return elm.AddChild(sp, 0);
            }

            #region IDisposable メンバ
            public void Dispose() {
                qvSelector = null;
            }
            #endregion

            public class ProcData {
                public Point drawPos;
                public Location cellLoc;
                public TerrainPieceTemplate.TerrainPolygonSet tpSet;
                public int hgap;
                public ProcData(Location l) {
                    this.cellLoc = l;
                }
            }
        }

    }


}
