﻿using System;
using System.Collections.Generic;
using TSLab.Script;
using TSLab.Script.Handlers;
using TSLab.Script.Helpers;


namespace ZigZagMS_
{
	public class ZigZagMS : IDouble2DoubleHandler
	{
		[HandlerParameter(true, "0.3", Min = "0", Max = "1", Step = "0.1")]
		public int ExtProcent { get; set; }

		[HandlerParameter(true, "0", Min = "0", Max = "1", Step = "1")]
		public int ExtCurrentBar { get; set; }

		public IList<double> Execute(IList<double> source)
		{
			var P = source;
			var ZZMS = new double[P.Count];
			double Procent,min,max;
			int m,i0=0;
			
			Procent=ExtProcent*0.01; 
			
			for(int i = 0; i < P.Count; i++)
			{
				ZZMS[i]=0;
			}
			
			min=P[1];
			max=min;
			m=0;//m=0:building the first left point of ZigZag
			for(int i = 2; i < P.Count; i++)
			{
				if (P[i]>max)
  				{
					max=P[i];
					if (m!=2)//m=1:building the down-point (min) of ZigZag
   					{
						if (max-min>=Procent*min)//min (m!=2) end,max (m=2) begin
    					{
							m=2;
							ZZMS[i]=max;
							i0=i;
							min=max;
    					}
					 	else ZZMS[i]=0.0;//max-min=miser,(m!=2) continue
   					}
					else //max (m=2) continue
   					{
						ZZMS[i0]=0.0;
						ZZMS[i]=max;
						i0=i;
						min=max;
  					}
				}
				else 
					if (P[i]<min)
  					{
						min=P[i];
   						if (m!=1)//m=2:building the up-point (max) of ZigZag
   						{
   							if (max-min>=Procent*max)//max (m!=1) end,min (m=1) begin
    						{
   								m=1;
   								ZZMS[i]=min;
   								i0=i;
   								max=min;
    						}
   							else ZZMS[i]=0.0;//max-min=miser,(m!=1) continue
   						}
   						else //min (m=1) continue
   						{
   							ZZMS[i0]=0.0;
   							ZZMS[i]=min;
   							i0=i;
   							max=min;
  						}
					}
					else ZZMS[i]=0.0;
			}
			if (ZZMS[0]==0.0) ZZMS[0]=P[0];
			
			if(ExtCurrentBar==1)
			{	
				if(ZZMS[P.Count-1]==0) ZZMS[P.Count-1]=P[P.Count-1];
			}
			
			return ZZMS;
		}
	}
}