import * as i0 from '@angular/core';
import { Injectable, EventEmitter, Directive, Input, Output } from '@angular/core';
import * as i1 from '@angular/common';
import * as i3 from '@ironsource/fusion-ui/services/unique-id';
import { isNullOrUndefined, isNumber, isDateString } from '@ironsource/fusion-ui/utils';
import * as i5 from '@ironsource/fusion-ui/services/colors';
import * as i2 from '@ironsource/fusion-ui/pipes/numbers';
import * as i6 from '@ironsource/fusion-ui/pipes/clone';
import { ArcElement, LineElement, BarElement, PointElement, LineController, BarController, PieController, ScatterController, CategoryScale, LinearScale, Filler, Tooltip, Chart } from 'chart.js';

/*
 * Created on 2020.4.4 By Andy Kononenko (andyk@ironsrc.com)
 */

var ChartType;
(function (ChartType) {
    ChartType["Line"] = "line";
    ChartType["StackedLine"] = "stackedLine";
    ChartType["Bar"] = "bar";
    ChartType["StackedBar"] = "stackedBar";
    ChartType["Doughnut"] = "doughnut";
    ChartType["Pie"] = "pie";
})(ChartType || (ChartType = {}));

const FLAG_BASE_URL = 'https://fusion.ironsrc.net/assets/flags/v4/';
const ICONS_BASE_URL = 'https://fusion.ironsrc.net/assets/icons/';
const COUNTRIES = {
    Afghanistan: 'af',
    'Aland Islands': 'ax',
    Albania: 'al',
    Algeria: 'dz',
    'American Samoa': 'as',
    Andorra: 'ad',
    Angola: 'ao',
    Anguilla: 'ai',
    Antarctica: 'aq',
    'Antigua and Barbuda': 'ag',
    Argentina: 'ar',
    Armenia: 'am',
    Aruba: 'aw',
    Australia: 'au',
    Austria: 'at',
    Azerbaijan: 'az',
    Bahamas: 'bs',
    Bahrain: 'bh',
    Bangladesh: 'bd',
    Barbados: 'bb',
    Belarus: 'by',
    Belgium: 'be',
    Belize: 'bz',
    Benin: 'bj',
    Bermuda: 'bm',
    Bhutan: 'bt',
    Bolivia: 'bo',
    'Bosnia and Herzegovina': 'ba',
    Botswana: 'bw',
    'Bouvet Island': 'bv',
    Brazil: 'br',
    'British Indian Ocean Territory': 'io',
    'Brunei Darussalam': 'bn',
    Bulgaria: 'bg',
    'Burkina Faso': 'bf',
    Burundi: 'bi',
    Cambodia: 'kh',
    Cameroon: 'cm',
    Canada: 'ca',
    'Cape Verde': 'cv',
    'Caribbean Netherlands': 'bq',
    'Cayman Islands': 'ky',
    'Central African Republic': 'cf',
    Chad: 'td',
    Chile: 'cl',
    China: 'cn',
    'Christmas Island': 'cx',
    'Cocos (Keeling) Islands': 'cc',
    Colombia: 'co',
    Comoros: 'km',
    Congo: 'cg',
    'Congo, The Democratic Republic of the': 'cd',
    'Cook Islands': 'ck',
    'Costa Rica': 'cr',
    'Cote D`Ivoire': 'ci',
    Croatia: 'hr',
    Cuba: 'cu',
    Curacao: 'cw',
    Cyprus: 'cy',
    'Czech Republic': 'cz',
    Denmark: 'dk',
    Djibouti: 'dj',
    Dominica: 'dm',
    'Dominican Republic': 'do',
    'East Timor': 'tl',
    Ecuador: 'ec',
    Egypt: 'eg',
    'El Salvador': 'sv',
    'Equatorial Guinea': 'gq',
    Eritrea: 'er',
    Estonia: 'ee',
    Ethiopia: 'et',
    'Falkland Islands (Malvinas)': 'fk',
    'Faroe Islands': 'fo',
    Fiji: 'fj',
    Finland: 'fi',
    France: 'fr',
    'French Guiana': 'gf',
    'French Polynesia': 'pf',
    'French Southern Territories': 'tf',
    Gabon: 'ga',
    Gambia: 'gm',
    Georgia: 'ge',
    Germany: 'de',
    Ghana: 'gh',
    Gibraltar: 'gi',
    Greece: 'gr',
    Greenland: 'gl',
    Grenada: 'gd',
    Guadeloupe: 'gp',
    Guam: 'gu',
    Guatemala: 'gt',
    Guernsey: 'gg',
    Guinea: 'gn',
    'Guinea-Bissau': 'gw',
    Guyana: 'gy',
    Haiti: 'ht',
    'Heard Island and McDonald Islands': 'hm',
    'Holy See (Vatican City State)': 'va',
    Honduras: 'hn',
    'Hong Kong': 'hk',
    Hungary: 'hu',
    Iceland: 'is',
    India: 'in',
    Indonesia: 'id',
    'Iran, Islamic Republic of': 'ir',
    Iraq: 'iq',
    Ireland: 'ie',
    'Isle of Man': 'im',
    Israel: 'il',
    Italy: 'it',
    Jamaica: 'jm',
    Japan: 'jp',
    Jersey: 'je',
    Jordan: 'jo',
    Kazakhstan: 'kz',
    Kenya: 'ke',
    Kiribati: 'ki',
    'Korea, Democratic People`s Republic of': 'kp',
    'Korea, Republic of': 'kr',
    Kosovo: 'xk',
    Kuwait: 'kw',
    Kyrgyzstan: 'kg',
    'Lao People`s Democratic Republic': 'la',
    Latvia: 'lv',
    Lebanon: 'lb',
    Lesotho: 'ls',
    Liberia: 'lr',
    Libya: 'ly',
    Liechtenstein: 'li',
    Lithuania: 'lt',
    Luxembourg: 'lu',
    Macau: 'mo',
    Macedonia: 'mk',
    Madagascar: 'mg',
    Malawi: 'mw',
    Malaysia: 'my',
    Maldives: 'mv',
    Mali: 'ml',
    Malta: 'mt',
    'Marshall Islands': 'mh',
    Martinique: 'mq',
    Mauritania: 'mr',
    Mauritius: 'mu',
    Mayotte: 'yt',
    Mexico: 'mx',
    'Micronesia, Federated States of': 'fm',
    'Moldova, Republic of': 'md',
    Monaco: 'mc',
    Mongolia: 'mn',
    Montenegro: 'me',
    Montserrat: 'ms',
    Morocco: 'ma',
    Mozambique: 'mz',
    Myanmar: 'mm',
    Namibia: 'na',
    Nauru: 'nr',
    Nepal: 'np',
    Netherlands: 'nl',
    'New Caledonia': 'nc',
    'New Zealand': 'nz',
    Nicaragua: 'ni',
    Niger: 'ne',
    Nigeria: 'ng',
    Niue: 'nu',
    'Norfolk Island': 'nf',
    'Northern Mariana Islands': 'mp',
    Norway: 'no',
    Oman: 'om',
    Pakistan: 'pk',
    Palau: 'pw',
    'Palestine, State of': 'ps',
    Panama: 'pa',
    'Papua New Guinea': 'pg',
    Paraguay: 'py',
    Peru: 'pe',
    Philippines: 'ph',
    Pitcairn: 'pn',
    Poland: 'pl',
    Portugal: 'pt',
    'Puerto Rico': 'pr',
    Qatar: 'qa',
    Reunion: 're',
    Romania: 'ro',
    'Russian Federation': 'ru',
    Rwanda: 'rw',
    'Saint Barthelemy': 'bl',
    'Saint Helena': 'sh',
    'Saint Kitts and Nevis': 'kn',
    'Saint Lucia': 'lc',
    'Saint Martin': 'mf',
    'Saint Pierre and Miquelon': 'pm',
    'Saint Vincent and the Grenadines': 'vc',
    Samoa: 'ws',
    'San Marino': 'sm',
    'Sao Tome and Principe': 'st',
    'Saudi Arabia': 'sa',
    Senegal: 'sn',
    Serbia: 'rs',
    Seychelles: 'sc',
    'Sierra Leone': 'sl',
    Singapore: 'sg',
    'Sint Maarten': 'sx',
    Slovakia: 'sk',
    Slovenia: 'si',
    'Solomon Islands': 'sb',
    Somalia: 'so',
    'South Africa': 'za',
    'South Georgia and the South Sandwich Islands': 'gs',
    'South Sudan': 'ss',
    Spain: 'es',
    'Sri Lanka': 'lk',
    Sudan: 'sd',
    Suriname: 'sr',
    'Svalbard and Jan Mayen': 'sj',
    Swaziland: 'sz',
    Sweden: 'se',
    Switzerland: 'ch',
    'Syrian Arab Republic': 'sy',
    Taiwan: 'tw',
    Tajikistan: 'tj',
    'Tanzania, United Republic of': 'tz',
    Thailand: 'th',
    Togo: 'tg',
    Tokelau: 'tk',
    Tonga: 'to',
    'Trinidad and Tobago': 'tt',
    Tunisia: 'tn',
    Turkey: 'tr',
    Turkmenistan: 'tm',
    'Turks and Caicos Islands': 'tc',
    Tuvalu: 'tv',
    Uganda: 'ug',
    Ukraine: 'ua',
    'United Arab Emirates': 'ae',
    'United Kingdom': 'gb',
    'United States Minor Outlying Islands': 'um',
    'United States': 'us',
    Uruguay: 'uy',
    Uzbekistan: 'uz',
    Vanuatu: 'vu',
    Venezuela: 've',
    Vietnam: 'vn',
    'Virgin Islands, British': 'vg',
    'Virgin Islands, U.S.': 'vi',
    'Wallis and Futuna': 'wf',
    'Western Sahara': 'eh',
    Yemen: 'ye',
    Zambia: 'zm',
    Zimbabwe: 'zw'
};
const TOOLTIP_ELEMENT_STYLE = `
  min-width: var(--chart-tooltip-min-width, 120px);
  max-width: var(--chart-tooltip-max-width);
  background:white;
  opacity:1;
  pointer-events:none;
  position:absolute;
  z-index: var(--chart-tooltip-z-index, 1001);
  padding: 8px;
  box-shadow: 0px 4px 8px -2px rgba(16, 24, 40, 0.12);
  border: 1px solid #e4e4e4;
  border-radius: 6px;
  transform: translate(-50%, 0);
  transition: all .1s ease;
`;
const WRAPPER_STYLE = `
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px
`;
const HEADER_ROW_STYLE = `
    display: flex;
    align-items: center;
    gap: 4px;
    font-family: Inter;
    font-size: 13px;
    font-style: normal;
    font-weight: 500;
    line-height: 20px;
    overflow: hidden;
    color: var(--text-primary, #202020);
    text-overflow: ellipsis;
    white-space: nowrap;
`;
const BODY_ROWS_WRAPPER = `
    display: flex;
    flex-direction: column;
    gap: 4px;
`;
const BODY_ROW_STYLE = `
    display: flex;
    align-items: center;
    gap: 4px;
    font-family: Inter;
    font-size: 13px;
    font-style: normal;
    font-weight: 400;
    line-height: 20px;
    letter-spacing: -0.039px;
`;
const ROUND_INDICATOR_ELEMENT_STYLE = `
    height:12px;
    width:12px;
    display:block;
    border-radius:2px
`;
const BODY_ROW_ICON_STYLE = `
width: 16px;
height: 16px;
background-color: var(--action-active, #808080);
`;
const TITLE_ROW_ICON_STYLE = `
width: 16px;
height: 16px;
background-color: var(--action-active, #808080);
`;
const BODY_ROW_LABEL_STYLE = `
    display: block;
    flex: 1;
    overflow: hidden;
    color: var(--text-secondary, #646464);
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 4px;
`;
const BODY_ROW_VALUE_STYLE = `
margin-left: auto;
color: var(--text-secondary, #646464);
`;
const FOOTER_ROW_STYLE = `
    font-family: Inter;
    font-size: 13px;
    font-style: normal;
    font-weight: 500;
    line-height: 20px;
    color: var(--text-primary, #202020);
    display: flex;
    gap: 4px;
`;
function getOrCreateTooltip(chart) {
    let tooltipEl = chart.canvas.parentNode.querySelector('div');
    if (!tooltipEl) {
        tooltipEl = document.createElement('div');
        tooltipEl.className = 'fu-chart-tooltip';
        tooltipEl.style.cssText = TOOLTIP_ELEMENT_STYLE;
        const table = document.createElement('div');
        table.style.cssText = WRAPPER_STYLE;
        table.classList.add('fu-chart-tooltip-wrapper');
        tooltipEl.appendChild(table);
        chart.canvas.parentNode.appendChild(tooltipEl);
    }
    return tooltipEl;
}
function generateTooltipHeaderElement(title) {
    const headerRowEl = document.createElement('div');
    headerRowEl.style.cssText = HEADER_ROW_STYLE;
    const countryCode = COUNTRIES[title];
    if (countryCode) {
        const flagImage = document.createElement('img');
        flagImage.style.width = '16px';
        flagImage.style.height = '16px';
        flagImage.style.borderRadius = '50%';
        flagImage.src = FLAG_BASE_URL + countryCode + '.svg';
        headerRowEl.appendChild(flagImage);
    }
    else if (title.includes(',(')) {
        const tileSplit = title.split(',(');
        title = tileSplit[0];
        const icon = tileSplit[1].replace(')', '');
        if (!!icon) {
            const iconImg = document.createElement('div');
            iconImg.style.cssText = TITLE_ROW_ICON_STYLE;
            iconImg.style.mask = `url(${ICONS_BASE_URL + 'v4/branded/' + icon.toLowerCase() + '.svg'}) no-repeat center`;
            headerRowEl.appendChild(iconImg);
        }
    }
    const text = document.createTextNode(title);
    headerRowEl.appendChild(text);
    return headerRowEl;
}
function generateTooltipFooterElement(footer) {
    const parsedBody = splitLastOccurrence(footer, ':');
    const label = parsedBody[0];
    const val = parsedBody[1];
    const footerRow = document.createElement('div');
    footerRow.style.cssText = FOOTER_ROW_STYLE;
    footerRow.innerHTML = `<div>${label}</div><div style="margin-left: auto">${val}</div>`;
    return footerRow;
}
function generateTooltipBodyRow({ tooltip, i, body }) {
    const bodyRow = document.createElement('div');
    bodyRow.style.cssText = BODY_ROW_STYLE;
    const colors = tooltip.labelColors[i];
    const colorDiv = document.createElement('div');
    const labelColor = colors.borderColor === '#fcfcfc'.toUpperCase() ? colors.backgroundColor : colors.borderColor;
    colorDiv.style.cssText = `
    background:${labelColor};
    border-color:${labelColor};
    ${ROUND_INDICATOR_ELEMENT_STYLE}
  `;
    const parsedBody = splitLastOccurrence(body[0], ':');
    const label = parsedBody[0];
    const val = parsedBody[1];
    const labelDiv = document.createElement('div');
    labelDiv.style.cssText = BODY_ROW_LABEL_STYLE;
    labelDiv.innerText = label;
    const valueDiv = document.createElement('div');
    valueDiv.style.cssText = BODY_ROW_VALUE_STYLE;
    valueDiv.innerText = val;
    bodyRow.appendChild(colorDiv);
    const icon = tooltip.dataPoints.map(d => d.dataset.icon ?? null).filter(Boolean)[i];
    if (!!icon) {
        const iconImg = document.createElement('div');
        iconImg.style.cssText = BODY_ROW_ICON_STYLE;
        iconImg.style.mask = `url(${ICONS_BASE_URL + icon + '.svg'}) no-repeat center`;
        bodyRow.appendChild(iconImg);
    }
    bodyRow.appendChild(labelDiv);
    bodyRow.appendChild(valueDiv);
    return bodyRow;
}
function externalV4TooltipHandler(context) {
    const { chart, tooltip } = context;
    const tooltipEl = getOrCreateTooltip(chart);
    const bodySortReverse = chart?.config?._config?.options?.plugins?.tooltip?.sortReverse ?? false;
    if (tooltip.opacity === 0) {
        tooltipEl.style.opacity = 0;
        return;
    }
    if (tooltip.body) {
        const titleLines = tooltip.title || [];
        const bodyLines = tooltip.body.map(b => b.lines);
        const footerLine = tooltip.footer || [];
        const tooltipHead = document.createElement('div');
        tooltipHead.style.cssText = HEADER_ROW_STYLE;
        const tooltipBody = document.createElement('div');
        tooltipBody.style.cssText = BODY_ROWS_WRAPPER;
        const tooltipRoot = tooltipEl.querySelector('div.fu-chart-tooltip-wrapper');
        if (chart.config?._config?.type !== 'doughnut') {
            titleLines.forEach((title) => {
                if (typeof title !== 'string' && title.tagName === 'IMG') {
                    tooltipHead.appendChild(title);
                }
                else {
                    const tr = generateTooltipHeaderElement(title);
                    tooltipHead.appendChild(tr);
                }
            });
        }
        bodyLines.forEach((body, i) => {
            if (bodyLines.length > 1 && bodySortReverse) {
                tooltipBody.prepend(generateTooltipBodyRow({ tooltip, i, body }));
            }
            else {
                tooltipBody.appendChild(generateTooltipBodyRow({ tooltip, i, body }));
            }
        });
        while (tooltipRoot.firstChild) {
            tooltipRoot.firstChild.remove();
        }
        if (tooltipHead.textContent.trim().length) {
            tooltipRoot.appendChild(tooltipHead);
        }
        tooltipRoot.appendChild(tooltipBody);
        if (footerLine?.length && bodyLines?.length > 1) {
            tooltipRoot.appendChild(generateTooltipFooterElement(footerLine[0]));
        }
    }
    const { offsetLeft: positionX, offsetTop: positionY } = chart.canvas;
    const maxBottomPoint = chart.canvas.clientHeight + 90;
    const tooltipYPosition = tooltip.caretY + tooltipEl.clientHeight;
    const yPositionAdjustment = maxBottomPoint < tooltipYPosition ? -15 : 0;
    const chartRect = chart.canvas.getBoundingClientRect();
    const tooltipOffset = positionX + 30 + tooltip.width / 2;
    const isOnTheRight = chart.width - (tooltip.caretX + tooltipOffset) < tooltip.width / 2 &&
        chartRect.left > tooltip.width / 2 &&
        chart.config?._config?.type !== 'doughnut';
    const tooltipLeft = tooltip.caretX + (positionX + 30 + tooltip.width / 2) * (isOnTheRight ? -1 : 1);
    tooltipEl.style.opacity = 1;
    tooltipEl.style.left = tooltipLeft + 'px';
    tooltipEl.style.top = positionY + tooltip.caretY + yPositionAdjustment + 'px';
}
function splitLastOccurrence(str, substring) {
    const lastIndex = str.lastIndexOf(substring);
    const before = str.slice(0, lastIndex);
    const after = str.slice(lastIndex + 1);
    return [before, after];
}

const BASE_DATASET_OPTIONS = {
    style_v1: {
        colorSettings: ['backgroundColor', 'borderColor', 'pointBorderColor', 'pointBackgroundColor'],
        fillOpacity: 50,
        seriesToShow: 7,
        lineOptions: {
            fill: false,
            hidden: false,
            pointBorderColor: '#ffffff'
        },
        barOptions: {
            borderWidth: 1,
            backgroundColor: [],
            borderColor: []
        },
        pieOptions: {
            backgroundColor: []
        }
    },
    style_v2: {
        colorSettings: ['backgroundColor', 'borderColor', 'pointBorderColor', 'pointBackgroundColor'],
        fillOpacity: 40,
        seriesToShow: 7,
        dateFormat: 'MMM dd, yyyy',
        lineOptions: {
            fill: false,
            hidden: false,
            pointBackgroundColor: '#ffffff'
        },
        barOptions: {
            borderWidth: 0,
            backgroundColor: [],
            borderColor: []
        },
        pieOptions: {
            backgroundColor: []
        }
    },
    style_v4: {
        colorSettings: ['backgroundColor', 'borderColor', 'pointBorderColor', 'pointHoverBackgroundColor'],
        fillOpacity: 10,
        seriesToShow: 7,
        dateFormat: 'MMM dd',
        lineOptions: {
            fill: false,
            hidden: false,
            borderWidth: 2,
            tension: 0.4,
            pointHoverBackgroundColor: '#fcfcfc'
        },
        barOptions: {
            borderRadius: 4,
            borderWidth: 0,
            backgroundColor: [],
            borderColor: []
        },
        pieOptions: {
            cutout: '73%',
            borderWidth: 2,
            hoverBorderWidth: 2,
            backgroundColor: []
        }
    }
};
/**
 * ChartJS Global Configuration
 * http://www.chartjs.org/docs/#chart-configuration-global-configuration
 */
const CHART_CONFIGURATIONS = {
    style_v1: {
        colorsPalette: 'base',
        dottedLineForToday: true,
        calculateMaxForAll: true,
        calculatePieSummary: true,
        responsive: true,
        maintainAspectRatio: false,
        resizeDelay: 0,
        interaction: {
            mode: 'nearest'
        },
        plugins: {
            legend: {
                display: false
            },
            title: {
                display: false
            },
            subtitle: {
                display: true
            },
            tooltip: {
                enabled: true,
                backgroundColor: '#fff',
                titleFont: { size: 16 },
                titleColor: '#172D4C',
                bodyFont: { size: 16 },
                bodyColor: '#172D4C',
                borderColor: 'rgba(194,205,215,1)',
                borderWidth: 1,
                cornerRadius: 0,
                caretSize: 10,
                xPadding: 10,
                yPadding: 10
            }
        },
        layout: {
            padding: {
                top: 10
            }
        },
        elements: {
            line: {
                borderWidth: 1,
                tension: 0
            },
            point: {
                borderWidth: 1,
                pointRadius: 2,
                pointHoverRadius: 3,
                pointHitRadius: 2
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                ticks: {
                    color: '#678099',
                    padding: 7,
                    maxRotation: 0
                },
                grid: {
                    display: false,
                    drawBorder: false
                }
            },
            y: {
                beginAtZero: true,
                ticks: {
                    color: '#678099',
                    padding: 10
                },
                grid: {
                    drawBorder: false,
                    lineWidth: 1,
                    color: '#e1e6eb'
                }
            }
        }
    },
    style_v2: {
        colorsPalette: 'base',
        dottedLineForToday: true,
        calculateMaxForAll: true,
        calculatePieSummary: true,
        responsive: true,
        maintainAspectRatio: false,
        resizeDelay: 0,
        interaction: {
            mode: 'nearest'
        },
        plugins: {
            legend: {
                display: false
            },
            title: {
                display: false
            },
            subtitle: {
                display: true
            },
            tooltip: {
                enabled: true,
                backgroundColor: '#fff',
                titleFont: { size: 16 },
                titleColor: '#172D4C',
                bodyFont: { size: 16 },
                bodyColor: '#172D4C',
                borderColor: 'rgba(194,205,215,1)',
                borderWidth: 1,
                cornerRadius: 0,
                caretSize: 10,
                xPadding: 10,
                yPadding: 10
            }
        },
        layout: {
            padding: {
                top: 10
            }
        },
        elements: {
            line: {
                borderWidth: 2,
                tension: 0
            },
            point: {
                borderWidth: 2,
                radius: 3,
                hoverRadius: 4,
                hitRadius: 3
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                ticks: {
                    color: '#7b838c',
                    font: { size: 11 },
                    padding: 0
                },
                grid: {
                    drawBorder: false,
                    display: false
                }
            },
            y: {
                beginAtZero: true,
                ticks: {
                    color: '#7b838c',
                    font: { size: 11 },
                    padding: 16
                },
                grid: {
                    drawBorder: false,
                    lineWidth: 1,
                    color: '#e5e7e9'
                }
            }
        }
    },
    style_v4: {
        dottedLineForToday: true,
        calculateMaxForAll: true,
        calculatePieSummary: true,
        responsive: true,
        maintainAspectRatio: false,
        resizeDelay: 0,
        interaction: {
            mode: 'point'
        },
        plugins: {
            legend: {
                display: false
            },
            title: {
                display: false
            },
            subtitle: {
                display: true
            },
            tooltip: {
                enabled: false,
                position: 'nearest',
                sortReverse: true,
                external: externalV4TooltipHandler
            }
        },
        layout: {
            padding: {
                top: 10
            }
        },
        elements: {
            line: {
                borderWidth: 2,
                tension: 0.4
            },
            point: {
                radius: 0,
                hitRadius: 8,
                hoverBorderWidth: 2,
                pointHoverBackgroundColor: '#fcfcfc'
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                ticks: {
                    color: '#646464',
                    font: { size: 12, weight: 400 },
                    padding: 0,
                    minRotation: 0,
                    maxRotation: 0,
                    autoSkip: true
                },
                grid: {
                    drawBorder: false,
                    display: false
                }
            },
            y: {
                border: {
                    display: false
                },
                beginAtZero: true,
                ticks: {
                    color: '#646464',
                    font: { size: 12, weight: 400 },
                    padding: 8
                },
                grid: {
                    lineWidth: 1,
                    color: '#E4E4E4',
                    display: true,
                    tickLength: 8,
                    drawTicks: false
                }
            }
        }
    }
};

const ERROR_MESSAGES = {
    data_parse_exception: 'Data parsing exception: data values for chart not exist',
    configuration_not_valid: 'chart configuration error, data field are required to render char type of'
};

class ChartDataService {
    parseChartData(data, type, isStacked = false) {
        let parsed = void 0; // void 0 returns undefined and can not be overwritten while undefined can be overwritten.
        switch (type) {
            case ChartType.Line:
                parsed = {
                    labels: this.getLegends(data),
                    datasets: this.getDataSet(data)
                };
                break;
            case ChartType.Bar:
                parsed = this.getGroupedDataSet(data);
                break;
            case ChartType.Doughnut:
            case ChartType.Pie:
                parsed = this.getPieData(data);
                break;
        }
        if (!parsed) {
            throw new Error(`${ERROR_MESSAGES.configuration_not_valid} ${type}`);
        }
        return parsed;
    }
    setLastDotted(dataset) {
        const dottedOption = { borderDash: [3, 5] };
        // duplicate dataset with dotted option
        return dataset.reduce((acc, item) => {
            const count = item.data.length;
            if (count > 2) {
                const data1 = [...item.data];
                const data2 = [...item.data];
                data1.pop();
                data2.fill(null, 0, count - 2);
                acc.push({ ...item, ...{ data: data1 } }, { ...item, ...{ data: data2 }, ...dottedOption });
            }
            else {
                // just update with "doted"
                acc.push({ ...item, ...dottedOption });
            }
            return acc;
        }, []);
    }
    getDataSet(data) {
        const dataset = [];
        const dataKeys = Object.keys(data.data);
        data.legends.forEach((label, idx) => {
            const dataValues = [];
            dataKeys.forEach(key => {
                dataValues.push(data.data[key][idx]);
            });
            dataset.push(
            // @ts-ignore
            Object.assign({
                id: label.id,
                label: label.displayName,
                data: dataValues,
                displayFormat: !isNullOrUndefined(label.displayFormat) ? label.displayFormat : null,
                icon: !isNullOrUndefined(label.icon) ? label.icon : null
            }, !isNullOrUndefined(label.hidden) ? { hidden: label.hidden } : {}));
        });
        return dataset;
    }
    getGroupedDataSet(data) {
        const legends = [];
        const dataset = [];
        data.legends.forEach((label, idx) => {
            // @ts-ignore
            legends.push(label.displayName);
        });
        Object.keys(data.data).forEach((key) => {
            dataset.push({
                label: key,
                data: data.data[key]
            });
        });
        return {
            labels: legends,
            datasets: dataset
        };
    }
    getLegends(data) {
        return Object.keys(data.data);
    }
    getTotals(data) {
        const legends = [];
        const dataset = [];
        data.legends.forEach((label, idx) => {
            // @ts-ignore
            legends.push(label.displayName);
            if (!isNullOrUndefined(label.value)) {
                dataset.push(label.value);
            }
            else if (!isNullOrUndefined(data.data)) {
                const dataKeys = Object.keys(data.data);
                dataset.push(Number(dataKeys
                    .reduce((sum, key) => {
                    sum += data.data[key][idx];
                    return sum;
                }, 0)
                    .toFixed(2)));
            }
            else {
                throw new Error(ERROR_MESSAGES.data_parse_exception);
            }
        });
        return {
            labels: legends,
            datasets: [
                {
                    data: dataset
                }
            ]
        };
    }
    getPieData(data) {
        const legends = [];
        const dataset = [];
        if (Array.isArray(data.data)) {
            data.data.forEach(item => {
                legends.push(item.displayText);
                dataset.push(item.value);
            });
        }
        else {
            Object.keys(data.data)
                .map(key => [key, data.data[key]])
                .forEach(item => {
                legends.push(item[0]);
                dataset.push(item[1]);
            });
        }
        return {
            labels: legends,
            datasets: [
                {
                    data: dataset,
                    legends
                }
            ]
        };
    }
    static { this.ɵfac = function ChartDataService_Factory(t) { return new (t || ChartDataService)(); }; }
    static { this.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: ChartDataService, factory: ChartDataService.ɵfac }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ChartDataService, [{
        type: Injectable
    }], null, null); })();

const HoverVerticalLine = {
    id: 'hoverVerticalLine',
    beforeDraw: chart => {
        if (chart.getActiveElements().length) {
            const activePoint = chart.getActiveElements()[0];
            const chartArea = chart.chartArea;
            const ctx = chart.ctx;
            ctx.save();
            // grey vertical hover line - full chart height
            ctx.beginPath();
            ctx.moveTo(activePoint.element.x, chartArea.top);
            ctx.lineTo(activePoint.element.x, chartArea.bottom);
            ctx.lineWidth = 1;
            ctx.strokeStyle = 'rgba(0,0,0, 0.1)';
            ctx.stroke();
            ctx.restore();
        }
    }
};

Chart.register(ArcElement, LineElement, BarElement, PointElement, LineController, BarController, PieController, ScatterController, CategoryScale, LinearScale, Filler, Tooltip, HoverVerticalLine);
class ChartBaseComponent {
    set data(value) {
        this._data = { ...value };
    }
    /** @internal */
    set options(value) {
        if (!!value) {
            this._options = { ...this._options, ...value };
        }
    }
    /** @internal */
    get options() {
        return this._options;
    }
    constructor(datePipe, currencyPipe, decimalPipe, percentPipe, numberToStringPipe, uniqueIdService, dataParseService, colorsService, elemRef, clonePipe) {
        this.datePipe = datePipe;
        this.currencyPipe = currencyPipe;
        this.decimalPipe = decimalPipe;
        this.percentPipe = percentPipe;
        this.numberToStringPipe = numberToStringPipe;
        this.uniqueIdService = uniqueIdService;
        this.dataParseService = dataParseService;
        this.colorsService = colorsService;
        this.elemRef = elemRef;
        this.clonePipe = clonePipe;
        this.afterDatasetInit = new EventEmitter();
        /** @internal */
        this.componentVersion = 2;
        this._options = {
            yAxisLines: 4
        };
        this.isStacked = false;
        this.legends = [];
    }
    ngOnInit() {
        this.id = this.id || `fs-chart-${this.uniqueIdService.getUniqueId()}`;
        this.type = this.type || ChartType.Line;
        if (this.type === ChartType.StackedLine) {
            this.type = ChartType.Line;
            this.isStacked = true;
        }
        else if (this.type === ChartType.StackedBar) {
            this.type = ChartType.Bar;
            this.isStacked = true;
        }
        if (this.type === ChartType.Doughnut) {
            this.pieSumLabel = this._data?.label;
        }
        this.elemRef.nativeElement.querySelector('div').id = this.id;
        this.ctx = this.elemRef.nativeElement.querySelector('canvas');
        this.canvasContent = this.ctx.getContext('2d');
        if (!isNullOrUndefined(this.ctx) && this._data && Object.keys(this._data).length) {
            this.setChart(this._data, this.type);
        }
    }
    ngOnDestroy() {
        if (this.chart) {
            this.chart.destroy();
            this.chart = void 0;
        }
    }
    ngOnChanges(changes) {
        if (!isNullOrUndefined(this.ctx) && changes.data && !changes.data.firstChange) {
            this.setChart(changes.data.currentValue, this.type);
        }
    }
    setChart(data, type) {
        this.yAxesFormat = this.getDisplayFormat(data) ?? data.displayFormat;
        this.chartData = this.dataParseService.parseChartData(data, type, this.isStacked);
        this.chartOptions = this.getChartOptions();
        this.legends = data.legends;
        if (!isNullOrUndefined(this.chart)) {
            this.chart.destroy();
        }
        this.chart = this.renderChart(this.ctx);
        if ((this.type === ChartType.Bar || this.type === ChartType.StackedBar) &&
            isNumber(this.options.showCharsAmountXLabels) &&
            !!this.chartData?.labels?.length) {
            this.barWidth = (this.chart.getDatasetMeta(0)?.xScale?.width ?? this.ctx.width) / this.chartData?.labels?.length;
            if (this.barWidth) {
                this.chartOptions.scales.x.ticks.callback = this.trimAxisXLabel.bind(this);
                this.chart.update();
            }
        }
        this.afterDatasetInit.emit(this.chartData.datasets);
    }
    // region chart datasets show / hide methods
    /** @internal */
    toggleDataset(label, recalculateYMax = false) {
        if ((this.type === ChartType.Bar || this.type === ChartType.StackedBar) && label.typeCheckbox) {
            this.filterBarData(label, recalculateYMax);
        }
        else {
            this.toggleLineDataset(label, recalculateYMax);
        }
    }
    filterBarData(label, recalculateYMax = false) {
        if (isNullOrUndefined(this.originalBarData)) {
            this.originalLabels = [...this.chart.data.labels];
            this.originalBarData = structuredClone(this.chart.data.datasets);
        }
        if (!label.labelVisible.value) {
            const otherDataIndex = this.getLabelIndex(label.id);
            if (otherDataIndex !== -1) {
                Object.keys(this.chart.data.datasets).forEach(key => {
                    this.chart.data.datasets[key].data.splice(otherDataIndex, 1);
                });
                this.chart.data.labels.splice(otherDataIndex, 1);
            }
        }
        else {
            this.chart.data.labels = [...this.originalLabels];
            this.chart.data.datasets = structuredClone(this.originalBarData);
        }
        if (recalculateYMax) {
            this.calcYAxes(this.chart?.options?.scales?.y);
        }
        this.chart.update();
    }
    getLabelIndex(labelId) {
        let index = -1;
        this.chart.data.labels.find((item, idx) => {
            if (index === -1) {
                if (Array.isArray(item) && item[0] === labelId) {
                    index = idx;
                }
                else {
                    index = item === labelId ? idx : -1;
                }
            }
        });
        return index;
    }
    toggleLineDataset(label, recalculateYMax = false) {
        this.chart.data.datasets
            .filter(item => {
            let thisLabel = item.label === label.label && (!isNullOrUndefined(item.id) ? item.id === label.id : true);
            return thisLabel;
        })
            .forEach(item => {
            item.hidden = !label.labelVisible.value;
        });
        if (recalculateYMax) {
            this.calcYAxes(this.chart?.options?.scales?.y);
        }
        this.chart.update('none');
    }
    // endregion
    // region chart dataset highlight methods
    /** @internal */
    highlightDataset(label) {
        const datasets = this.chart?.data.datasets;
        if (!isNullOrUndefined(label)) {
            this.setChartUnHoveredBGColor(label, datasets);
        }
        else {
            this.setChartHoveredBGColor(label, datasets);
        }
        this.chart.update();
    }
    setChartUnHoveredBGColor(label, datasets) {
        datasets.forEach((dataset, idx) => {
            const isOtherDataset = !isNullOrUndefined(dataset.id) ? dataset.id !== label.id : idx !== label.id;
            if (isOtherDataset || this.type === ChartType.Doughnut) {
                if (this.type === ChartType.Line) {
                    dataset.borderColor = dataset.backgroundColor;
                }
                else if (this.type === ChartType.Bar) {
                    dataset.backgroundColor = dataset.backgroundColor.replace(',1)', ',0.1)');
                }
                else if (this.type === ChartType.Doughnut) {
                    dataset.backgroundColor.forEach((color, idx) => {
                        if (idx !== label.id) {
                            dataset.backgroundColor[idx] = dataset.backgroundColor[idx].replace(',1)', ',0.1)');
                        }
                    });
                }
            }
            else {
                if (this.type === ChartType.Line) {
                    dataset.backgroundColor = dataset.backgroundColor.replace('0.1)', '0.7)');
                }
            }
        });
    }
    setChartHoveredBGColor(label, datasets) {
        datasets.forEach((dataset, idx) => {
            if (this.type === ChartType.Line) {
                dataset.borderColor = dataset.backgroundColor.replace('0.1)', '1)');
                dataset.backgroundColor = dataset.backgroundColor.replace('0.7)', '0.1)');
            }
            else if (this.type === ChartType.Bar) {
                dataset.backgroundColor = dataset.backgroundColor.replace(',0.1)', ',1)');
            }
            else if (this.type === ChartType.Doughnut) {
                dataset.backgroundColor.forEach((color, idx) => {
                    dataset.backgroundColor[idx] = dataset.backgroundColor[idx].replace(',0.1)', ',1)');
                });
            }
        });
    }
    // endregion
    /** @internal */
    addDatasetStyleOptions(isLastDotted = true) {
        const palette = this.getColors();
        const datasetOptions = this.getDataSetOptionsByStyleVersion(this.componentVersion);
        const bgOpacity = datasetOptions.fillOpacity;
        if (this.type === ChartType.Line) {
            this.addDatasetLineStyleOptions(datasetOptions, isLastDotted, palette, bgOpacity);
        }
        else if (this.type === ChartType.Bar) {
            this.addDatasetBarStyleOptions(datasetOptions, palette, bgOpacity);
        }
        else if (this.type === ChartType.Pie || this.type === ChartType.Doughnut) {
            this.addDatasetPieStyleOptions(datasetOptions);
        }
    }
    getColors() {
        const palette = this.colorsService.getColorPalette(this.componentVersion);
        const legends = this._data.legends;
        // todo: need to check this case for stacked bar (it look like related to Object.keys(data) not for label).
        const customPalette = Array.isArray(legends) && legends.some(legend => !!legend.color)
            ? legends.map((legend, idx) => {
                return !isNullOrUndefined(legend.color)
                    ? legend.color
                    : !isNullOrUndefined(palette[idx])
                        ? palette[idx]
                        : '#' + Math.floor(Math.random() * 16777215).toString(16); // no color - gen random
            })
            : palette;
        return customPalette;
    }
    addDatasetLineStyleOptions(datasetOptions, isLastDotted, palette, bgOpacity) {
        const colorKeys = datasetOptions.colorSettings;
        const seriesToShow = datasetOptions.seriesToShow;
        const lineOptions = datasetOptions.lineOptions;
        const dateFormat = datasetOptions.dateFormat ?? 'MMM dd, yyyy';
        const isOneDataPoint = this.chartData.labels.length === 1;
        // set bg fill options
        lineOptions.fill = this.isStacked;
        if (this.componentVersion === 4) {
            lineOptions.pointRadius = isOneDataPoint ? 3 : 0;
            lineOptions.clip = 5;
            colorKeys.push('pointBackgroundColor');
        }
        bgOpacity = this.componentVersion === 4 ? bgOpacity : bgOpacity / 2;
        this.chartData.datasets = this.chartData.datasets.map((item, idx) => {
            const dataGroupOptions = colorKeys.reduce((resultOptions, colorOption) => {
                const color = this._data?.legends[idx]?.color || palette[idx];
                switch (colorOption) {
                    case 'backgroundColor':
                        resultOptions[colorOption] = this.colorsService.toRgba(color, bgOpacity);
                        break;
                    case 'pointBackgroundColor':
                        resultOptions[colorOption] = lineOptions[colorOption] ? lineOptions[colorOption] : color;
                        break;
                    case 'pointHoverBackgroundColor':
                        resultOptions[colorOption] = lineOptions[colorOption] ? lineOptions[colorOption] : color;
                        break;
                    case 'pointBorderColor':
                        resultOptions[colorOption] = lineOptions[colorOption] ? lineOptions[colorOption] : color;
                        break;
                    default:
                        resultOptions[colorOption] = color;
                }
                return resultOptions;
            }, {});
            // hide series over limit if not set
            if (!isNullOrUndefined(item.hidden)) {
                lineOptions.hidden = item.hidden;
            }
            else {
                lineOptions.hidden = idx > seriesToShow - 1;
            }
            // set fill option from line to line on stacked line chart
            if (this.componentVersion === 4 && this.isStacked) {
                lineOptions.fill = idx !== 0 ? '-1' : 'start';
            }
            // set line options
            Object.assign(dataGroupOptions, lineOptions);
            return Object.assign(item, dataGroupOptions);
        });
        // format xAxis (dates)
        if (this.componentVersion !== 4) {
            this.chartData.labels = this.chartData.labels.map(lbl => {
                return isDateString(lbl) ? this.datePipe.transform(lbl, dateFormat) : lbl;
            });
        }
        // support for last point (if last point - today) - dotted line type
        if (isLastDotted) {
            this.chartData.datasets = this.dataParseService.setLastDotted(this.chartData.datasets);
        }
        // check for one data point (do center align)
        if (this.chartData.labels.length === 1) {
            this.chartData.labels = ['', this.chartData.labels[0], ''];
            this.chartData.datasets.forEach(dataset => {
                dataset.data = [null, dataset.data[0], null];
                // set point style for today and / yesterday
                if (isLastDotted) {
                    dataset['pointBackgroundColor'] = '#ffffff';
                    dataset['pointBorderColor'] = dataset.borderColor;
                }
                else {
                    dataset['pointBorderColor'] = dataset.borderColor;
                }
            });
        }
    }
    addDatasetBarStyleOptions(datasetOptions, palette, bgOpacity) {
        const barOptions = datasetOptions.barOptions;
        this.chartData.datasets = this.chartData.datasets.map((item, idx) => {
            if (this.componentVersion === 4) {
                barOptions.borderColor = palette[idx];
                barOptions.backgroundColor = this.colorsService.toRgba(palette[idx], 100);
                barOptions.hoverBackgroundColor = palette[idx];
                barOptions.borderWidth = 0;
                barOptions.barPercentage = 0.9;
                if (this.isStacked) {
                    barOptions.barPercentage = 0.5;
                    barOptions.borderWidth = 2;
                    barOptions.borderColor = '#FCFCFC';
                    barOptions.hoverBorderColor = '#FCFCFC';
                }
            }
            else {
                for (let i = 0; i < item.data.length; i++) {
                    barOptions.borderColor.push(palette[i]);
                    barOptions.backgroundColor.push(this.colorsService.toRgba(palette[i], bgOpacity));
                }
            }
            return Object.assign(item, barOptions);
        });
    }
    addDatasetPieStyleOptions(datasetOptions) {
        const pieOptions = datasetOptions.pieOptions;
        const piePalette = this.colorsService.getPieColorsPalette(this.componentVersion);
        const onlyOneData = this.chartData.datasets[0].data.length === 1;
        // add colors and labels
        pieOptions.backgroundColor = [];
        pieOptions.hoverBackgroundColor = [];
        pieOptions.hoverBorderWidth = pieOptions.hoverBorderWidth;
        pieOptions.borderWidth = !onlyOneData ? pieOptions.borderWidth : 0;
        this.chartData.datasets = this.chartData.datasets.map(item => {
            for (let i = 0; i < item.data.length; i++) {
                let color;
                if (Array.isArray(this._data.data)) {
                    color = this._data.data.find(part => part.displayText === this.chartData.labels[i]).color;
                }
                if (!color) {
                    color = piePalette[i] ? piePalette[i] : piePalette[piePalette.length - 1];
                }
                if (this.componentVersion === 4) {
                    pieOptions.backgroundColor.push(this.colorsService.toRgba(color, 100));
                    pieOptions.hoverBackgroundColor.push(color);
                    pieOptions.borderColor = '#FCFCFC';
                    pieOptions.hoverBorderWidth = 0;
                    pieOptions.hoverBorderColor = 'transparent';
                }
                else {
                    pieOptions.backgroundColor.push(color);
                }
            }
            return { ...item, ...pieOptions };
        });
    }
    getDisplayFormat(data) {
        if (data && Array.isArray(data.legends) && data.legends.length !== 0) {
            return data.legends[0].displayFormat || null;
        }
        return null;
    }
    getDataSetOptionsByStyleVersion(versionNumber = 2) {
        const options = BASE_DATASET_OPTIONS[`style_v${versionNumber}`]
            ? BASE_DATASET_OPTIONS[`style_v${versionNumber}`]
            : BASE_DATASET_OPTIONS.style_v2;
        return { ...options };
    }
    getChartOptionsByStyleVersion(versionNumber = 2) {
        const options = CHART_CONFIGURATIONS[`style_v${versionNumber}`]
            ? CHART_CONFIGURATIONS[`style_v${versionNumber}`]
            : CHART_CONFIGURATIONS.style_v2;
        return this.clonePipe.transform(options);
    }
    applyOptions() {
        return this.deepMerge(this.getChartOptionsByStyleVersion(this.componentVersion), this.options);
    }
    deepMerge(target, source) {
        for (const key of Object.keys(source)) {
            const currentTarget = target[key];
            const currentSource = source[key];
            if (currentTarget) {
                const objectSource = typeof currentSource === 'object';
                const objectTarget = typeof currentTarget === 'object';
                if (objectSource && objectTarget) {
                    void (Array.isArray(currentTarget) && Array.isArray(currentSource)
                        ? void (target[key] = currentTarget.concat(currentSource))
                        : void this.deepMerge(currentTarget, currentSource));
                    continue;
                }
            }
            target[key] = currentSource;
        }
        return target;
    }
    getChartOptions() {
        const options = { ...this.applyOptions() };
        // hide legends for bar chart type by default
        if (this.type === ChartType.Bar || this.type === ChartType.Pie || this.type === ChartType.Doughnut) {
            options.plugins.legend.display = false;
        }
        const isLastDotted = this.isLastDotted(options);
        // set style options for the chart
        this.addDatasetStyleOptions(isLastDotted);
        // set min/ max for yAxes if line
        if (this.type === ChartType.Line) {
            this.setLineChartOptions(options);
        }
        else if (this.type === ChartType.Bar) {
            this.setBarChartOptions(options);
        }
        else if (this.type === ChartType.Doughnut || this.type === ChartType.Pie) {
            this.setPieChartOptions(options);
        }
        const isV4InteractionIndex = this.componentVersion === 4 && options?.interaction?.mode === 'index';
        // region apply tooltip options
        options.plugins.tooltip = {
            ...options.plugins.tooltip,
            callbacks: {
                ...options.plugins.tooltip.callbacks,
                label: this.getTooltipLabel.bind(this),
                ...(isV4InteractionIndex
                    ? {
                        footer: this.calculateTotals.bind(this),
                        beforeTitle: this.getBeforeTitle.bind(this),
                        title: this.getTooltipDateTitle.bind(this)
                    }
                    : {})
            },
            ...(isLastDotted ? { filter: this.filterTooltip.bind(this) } : {})
        };
        options.plugins['hoverVerticalLine'] = false;
        if (this.type === ChartType.Line && isV4InteractionIndex) {
            options.plugins['hoverVerticalLine'] = true;
        }
        // end region
        return options;
    }
    setLineChartOptions(options) {
        // calculate line-point options (if more than 50 points on char)
        if (Array.isArray(this.chartData.datasets) && this.chartData.datasets.length !== 0 && this.chartData.datasets[0].data.length > 50) {
            options.elements.point.pointRadius = 0;
        }
        this.calcYAxes(options.scales.y);
        if (this.isStacked) {
            options.scales.y.stacked = true;
            this.chartData.datasets.forEach(dataset => {
                if (dataset.label === 'Sum') {
                    dataset['fill'] = false;
                }
            });
        }
        if (this.componentVersion === 4) {
            const datasetOptions = this.getDataSetOptionsByStyleVersion(this.componentVersion);
            const dateFormat = datasetOptions.dateFormat ?? 'MMM dd, yyyy';
            options.scales.x.ticks.callback = (index) => {
                const label = this.chartData.labels[index];
                const value = isDateString(label) ? this.datePipe.transform(label, dateFormat) : label;
                return value;
            };
        }
    }
    setBarChartOptions(options) {
        this.calcYAxes(options.scales.y);
        if (!this.isStacked) {
            if (this.chartSubject) {
                this.chartData.datasets.forEach(dataset => {
                    Object.assign(dataset, {
                        label: this.chartSubject
                    });
                });
            }
        }
        else {
            options.scales.x.stacked = true;
            options.scales.y.stacked = true;
            options.interaction = {
                intersect: false,
                mode: 'index',
                axis: 'x'
            };
            options.plugins.tooltip = {
                ...options.plugins.tooltip
            };
        }
    }
    trimAxisXLabel(index) {
        const label = this.chartData.labels[index];
        const len = Math.round(this.barWidth * (this._options?.showCharsAmountXLabels / 100));
        const isArray = Array.isArray(label);
        let labelText = isArray ? label[0] : label;
        if (labelText.length > len) {
            labelText = labelText.substring(0, len) + '...';
            return isArray ? [labelText, label[1]] : labelText;
        }
        return label;
    }
    setPieChartOptions(options) {
        delete options.scales;
        delete options.elements;
        if (options.calculatePieSummary) {
            this.pieDataSum = this.chartData.datasets[0].data.reduce((sum, item) => (sum += item), 0);
        }
    }
    isLastDotted(options) {
        // eslint-disable-next-line one-var
        const todayString = (() => {
            // eslint-disable-next-line one-var
            const d = new Date(), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear();
            return [year, month.length < 2 ? '0' + month : month, day.length < 2 ? '0' + day : day].join('-');
        })(), dataKeys = Object.keys(this._data?.data);
        return options.dottedLineForToday && dataKeys[dataKeys.length - 1] === todayString;
    }
    // region tooltip related methods
    filterTooltip(context) {
        return !context.dataset.borderDash;
    }
    getTooltipLabel(context) {
        const label = context.dataset.label ?? context.label ?? '';
        const val = context.parsed.y ?? context?.formattedValue?.replace(/,/g, '');
        const format = context.dataset.displayFormat ?? this.yAxesFormat;
        return ` ${label}: ${!!format ? this.getFormatted(val, format) : val}`;
    }
    calculateTotals(tooltipItem) {
        const format = this.yAxesFormat;
        const total = tooltipItem.reduce((acc, val) => acc + val.raw, 0);
        return `Total: ${!!format ? this.getFormatted(total, format) : total}`;
    }
    getBeforeTitle(data) {
        const legend = this.legends.find(legend => {
            return Array.isArray(legend.displayName)
                ? legend.displayName.join(',') === data[0].label
                : legend.displayName === data[0].label;
        });
        if (!!legend?.imageUrl) {
            const appImage = document.createElement('img');
            appImage.style.width = '20px';
            appImage.style.height = '20px';
            appImage.style.borderRadius = '4px';
            appImage.src = legend?.imageUrl;
            return appImage;
        }
        return null;
    }
    getTooltipDateTitle(data) {
        const label = data[0].label;
        const value = isDateString(label) ? this.datePipe.transform(label, 'MMM d, YYYY') : label;
        return value;
    }
    // endregion
    renderChart(ctx) {
        const opts = {
            type: this.type,
            data: this.chartData,
            options: this.chartOptions
        };
        // console.log('opts', opts);
        return new Chart(ctx, opts);
    }
    calcYAxes(yAxe) {
        const sets = this.options.calculateMaxForAll ? this.chartData.datasets : this.chartData.datasets.filter(item => !item.hidden);
        const tickCount = this.options.yAxisLines || 5;
        // region get max & min values
        const setsStacked = [{ data: [] }];
        // for staked we need to calculate sum of all data values in set
        if (this.isStacked) {
            setsStacked[0].data = sets.reduce((acc, item, index) => {
                item.data.forEach((val, idx) => {
                    if (acc[idx]) {
                        acc[idx] += val;
                    }
                    else {
                        acc[idx] = val;
                    }
                });
                return acc;
            }, []);
        }
        let [max, min] = (this.isStacked ? setsStacked : sets).reduce(([_max, _min], item) => [Math.max(_max, Math.max.apply(null, item.data)), Math.min(_min, Math.min.apply(null, item.data))], [-Infinity, 0]);
        // endregion
        const yAxeMaxAddPercent = this.options.yAxeMaxAddPercent;
        if (!!yAxeMaxAddPercent) {
            max = max + max * yAxeMaxAddPercent;
        }
        let stepSize;
        let formatCallbackObj;
        if (max <= 1 && min >= -1) {
            stepSize = 0.2;
            max = 1;
            formatCallbackObj = {};
        }
        else {
            const roundTo = Math.pow(10, parseInt(max.toString(), 10).toString().length - 1);
            const maxVal = Math.ceil((max / roundTo) * 10) * (roundTo / 10);
            stepSize = parseFloat(((maxVal - min) / tickCount).toFixed(2));
            max = stepSize * tickCount;
            formatCallbackObj = {
                callback: (value) => {
                    return value === 0 ? value : this.getFormatted(value, 'shortString');
                }
            };
        }
        yAxe.ticks = {
            ...yAxe.ticks,
            ...{
                min,
                max,
                stepSize
            },
            ...formatCallbackObj
        };
    }
    getFormatted(value, format) {
        let retVal = value.toString();
        if (!isNullOrUndefined(format)) {
            const formatter = format.split(':');
            value = isNumber(value) ? value : Number(value);
            switch (formatter[0]) {
                case 'currency':
                    retVal = this.currencyPipe.transform(value, 'USD', true);
                    break;
                case 'shortCurrency':
                    retVal =
                        '$' +
                            this.numberToStringPipe.transform(value, {
                                noSeparateBySpace: true,
                                precision: this.componentVersion === 4 ? 3 : undefined
                            });
                    break;
                case 'percent':
                    retVal = this.percentPipe.transform(value / 100, formatter[1]);
                    break;
                case 'number':
                    retVal = this.decimalPipe.transform(value, formatter[1]);
                    break;
                case 'shortString':
                    retVal = isNumber(value)
                        ? this.numberToStringPipe.transform(value, {
                            noSeparateBySpace: true,
                            precision: this.componentVersion === 4 ? 3 : undefined
                        })
                        : value;
                    break;
            }
        }
        return retVal;
    }
    static { this.ɵfac = function ChartBaseComponent_Factory(t) { return new (t || ChartBaseComponent)(i0.ɵɵdirectiveInject(i1.DatePipe), i0.ɵɵdirectiveInject(i1.CurrencyPipe), i0.ɵɵdirectiveInject(i1.DecimalPipe), i0.ɵɵdirectiveInject(i1.PercentPipe), i0.ɵɵdirectiveInject(i2.ShortNumberScaleSuffixPipe), i0.ɵɵdirectiveInject(i3.UniqueIdService), i0.ɵɵdirectiveInject(ChartDataService), i0.ɵɵdirectiveInject(i5.ColorsService), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i6.ClonePipe)); }; }
    static { this.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: ChartBaseComponent, inputs: { id: "id", type: "type", data: "data", options: "options", chartSubject: "chartSubject", loading: "loading", noData: "noData" }, outputs: { afterDatasetInit: "afterDatasetInit" }, features: [i0.ɵɵNgOnChangesFeature] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ChartBaseComponent, [{
        type: Directive
    }], () => [{ type: i1.DatePipe }, { type: i1.CurrencyPipe }, { type: i1.DecimalPipe }, { type: i1.PercentPipe }, { type: i2.ShortNumberScaleSuffixPipe }, { type: i3.UniqueIdService }, { type: ChartDataService }, { type: i5.ColorsService }, { type: i0.ElementRef }, { type: i6.ClonePipe }], { id: [{
            type: Input
        }], type: [{
            type: Input
        }], data: [{
            type: Input
        }], options: [{
            type: Input
        }], chartSubject: [{
            type: Input
        }], loading: [{
            type: Input
        }], noData: [{
            type: Input
        }], afterDatasetInit: [{
            type: Output
        }] }); })();

/**
 * Generated bundle index. Do not edit.
 */

export { BASE_DATASET_OPTIONS, CHART_CONFIGURATIONS, ChartBaseComponent, ChartDataService, ChartType };
//# sourceMappingURL=ironsource-fusion-ui-components-chart-common-base.mjs.map
