#property copyright "KK"
#property strict
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1

#property description "Single EMA line with selectable period via on-chart buttons."
#property description "5 EMA period options: 20, 50, 100, 200, 500"

#property indicator_color1  clrWhite
#property indicator_type1   DRAW_LINE
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
#property indicator_label1  "EMA"

input int EMA_Period_1 = 20;
input int EMA_Period_2 = 50;
input int EMA_Period_3 = 100;
input int EMA_Period_4 = 200;
input int EMA_Period_5 = 500;
input int ButtonX = 1450;
input int ButtonY = 200;

double dEMA_Main[];

int    EMA_Periods[5];
int    CurrentPeriodIndex = 0;
int    CurrentEMA_Period;
string ButtonNames[5];
int    EMA_Handles[5];

void OnInit()
{
    EMA_Periods[0] = EMA_Period_1;
    EMA_Periods[1] = EMA_Period_2;
    EMA_Periods[2] = EMA_Period_3;
    EMA_Periods[3] = EMA_Period_4;
    EMA_Periods[4] = EMA_Period_5;

    string gvName = "EMA_Period_Index_" + _Symbol + "_" + IntegerToString(_Period);
    if(GlobalVariableCheck(gvName))
    {
        CurrentPeriodIndex = (int)GlobalVariableGet(gvName);
        if(CurrentPeriodIndex < 0 || CurrentPeriodIndex > 4) CurrentPeriodIndex = 0;
    }
    CurrentEMA_Period = EMA_Periods[CurrentPeriodIndex];

    SetIndexBuffer(0, dEMA_Main, INDICATOR_DATA);
    ArraySetAsSeries(dEMA_Main, true);
    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0.0);
    PlotIndexSetString(0, PLOT_LABEL, "EMA " + IntegerToString(CurrentEMA_Period));

    for(int i = 0; i < 5; i++)
    {
        EMA_Handles[i] = iMA(_Symbol, _Period, EMA_Periods[i], 0, MODE_EMA, PRICE_CLOSE);
        if(EMA_Handles[i] == INVALID_HANDLE)
            Print("Error creating EMA handle for period ", EMA_Periods[i], ": ", GetLastError());
    }

    UpdateIndicatorName();
    CreateButtons();
}

void OnDeinit(const int reason)
{
    DeleteButtons();
    for(int i = 0; i < 5; i++)
        if(EMA_Handles[i] != INVALID_HANDLE) IndicatorRelease(EMA_Handles[i]);
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
    if(id == CHARTEVENT_OBJECT_CLICK)
    {
        for(int i = 0; i < 5; i++)
        {
            if(sparam == ButtonNames[i])
            {
                ObjectSetInteger(0, ButtonNames[i], OBJPROP_STATE, false);
                if(CurrentPeriodIndex == i) return;
                CurrentPeriodIndex = i;
                CurrentEMA_Period  = EMA_Periods[i];
                string gvName = "EMA_Period_Index_" + _Symbol + "_" + IntegerToString(_Period);
                GlobalVariableSet(gvName, CurrentPeriodIndex);
                PlotIndexSetString(0, PLOT_LABEL, "EMA " + IntegerToString(CurrentEMA_Period));
                UpdateButtons();
                UpdateIndicatorName();
                ChartSetSymbolPeriod(ChartID(), _Symbol, (ENUM_TIMEFRAMES)_Period);
                return;
            }
        }
    }
}

void CreateButtons()
{
    int bW = 70, bH = 25, bS = 5;
    for(int i = 0; i < 5; i++)
    {
        ButtonNames[i] = "EMA_Button_" + IntegerToString(EMA_Periods[i]);
        if(ObjectCreate(0, ButtonNames[i], OBJ_BUTTON, 0, 0, 0))
        {
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_XDISTANCE,    ButtonX);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_YDISTANCE,    ButtonY + (bH + bS) * i);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_XSIZE,        bW);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_YSIZE,        bH);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_CORNER,       CORNER_LEFT_UPPER);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_FONTSIZE,     9);
            ObjectSetString(0,  ButtonNames[i], OBJPROP_TEXT,         "EMA " + IntegerToString(EMA_Periods[i]));
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_COLOR,        clrWhite);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BGCOLOR,      (i == CurrentPeriodIndex) ? clrGreen : clrDarkSlateGray);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BORDER_COLOR, clrBlack);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_SELECTABLE,   false);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_SELECTED,     false);
        }
    }
}

void UpdateButtons()
{
    for(int i = 0; i < 5; i++)
        if(ObjectFind(0, ButtonNames[i]) >= 0)
        {
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BGCOLOR, (i == CurrentPeriodIndex) ? clrGreen : clrDarkSlateGray);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_STATE,   false);
        }
    ChartRedraw();
}

void DeleteButtons()
{
    for(int i = 0; i < 5; i++)
        if(ObjectFind(0, ButtonNames[i]) >= 0)
            ObjectDelete(0, ButtonNames[i]);
}

void UpdateIndicatorName()
{
    IndicatorSetString(INDICATOR_SHORTNAME, "KK_EMA_Multi_Period_v1 (" + IntegerToString(CurrentEMA_Period) + ")");
}

int OnCalculate(const int rates_total, const int prev_calculated,
                const datetime &Time[], const double &open[],
                const double &High[], const double &Low[], const double &close[],
                const long &tick_volume[], const long &volume[], const int &spread[])
{
    if(rates_total < 10) return 0;

    ArraySetAsSeries(dEMA_Main, true);

    int limit = (prev_calculated == 0) ? rates_total - 1 : rates_total - prev_calculated + 1;

    double EMABuffer[];
    ArraySetAsSeries(EMABuffer, true);

    if(CopyBuffer(EMA_Handles[CurrentPeriodIndex], 0, 0, limit + 1, EMABuffer) <= 0)
        return prev_calculated;

    for(int i = 0; i < limit && i < (int)ArraySize(EMABuffer); i++)
        dEMA_Main[i] = EMABuffer[i];

    return rates_total;
}
