
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/


/**
 * AUTO-GENERATED FILE. DO NOT MODIFY.
 */

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createHashMap, isObject, map, HashMap, isString, each } from 'tvrender/lib/core/util.js';
import { fillWeightsForPoints } from './scale-time/time-scale-point-weight-generator.js';
import { findClosestTimestamp, findClosestIndex } from './scale-time/find-time-range.js';
var uidBase = 0;
// const ordinalMetaInstanceById: Record<string, OrdinalMeta> = {} 
function convertToUTCDayStart(ts) {
  var shifted = new Date(ts * 1000);
  // ② 提取该日期的 UTC 年、月、日（因为 shifted 已经“落在”目标时区的日期中了）
  var year = shifted.getUTCFullYear();
  var month = shifted.getUTCMonth(); // 注意：月份从 0 开始
  var day = shifted.getUTCDate();
  // ③ 目标时区（UTC-8）的当地零点，在 UTC 下的时间戳应为：
  //     （“该日期 UTC 零点”）+ 8 小时
  var localMidUTC = Date.UTC(year, month, day);
  // 返回秒单位时间戳
  return localMidUTC;
}
var OrdinalMeta = /** @class */function () {
  function OrdinalMeta(opt) {
    // private _timePoints: TimePoint[];
    this.cache = null;
    this._appendCount = 0;
    this.categories = opt.categories || [];
    this.extraCategory = opt.extraCategory || [];
    this.loadMoreCategory = opt.loadMoreCategory;
    this._needCollect = opt.needCollect;
    this._deduplication = opt.deduplication;
    // this._timePoints = opt.timePoints;
    this._marksByWeight = opt.marksByWeight;
    this.dataInterval = opt.dataInterval;
    this.utcOffsetTime = opt.utcOffsetTime;
    this.cache = null;
    this.uid = ++uidBase;
  }
  OrdinalMeta.createByAxisModel = function (axisModel) {
    var option = axisModel.option;
    var data = option.data;
    var isSegmentedByTime = option.segmentedByTime;
    var timePoints = [];
    var marksByWeight = new HashMap();
    var formatInterval = option.dataInterval === '1D';
    // const windowId = axisModel.ecModel.get('windowId')
    var addItem = function (value, index) {
      var d = formatInterval ? convertToUTCDayStart(value - option.utcOffsetTime) : value * 1000;
      timePoints.push({
        originalTime: value,
        index: index,
        timestamp: d / 1000
      });
    };
    var categories = data && map(data, function (val, index) {
      var value = val;
      if (isSegmentedByTime) {
        addItem(value, index);
      }
      return getName(val);
    });
    var extraCategory = option.extraCategory && map(option.extraCategory, function (val, i) {
      var value = val;
      if (isSegmentedByTime) {
        var index = i + categories.length;
        addItem(value, index);
      }
      return getName(val);
    });
    if (timePoints.length) {
      fillWeightsForPoints(timePoints);
      for (var index = 0; index < timePoints.length; ++index) {
        var point = timePoints[index];
        var marksForWeight = marksByWeight.get(point.weight);
        if (marksForWeight === undefined) {
          marksForWeight = [];
          marksByWeight.set(point.weight, marksForWeight);
        }
        marksForWeight.push(point);
      }
    }
    // if (windowId && ordinalMetaInstanceById[windowId]) {
    //     return ordinalMetaInstanceById[windowId]
    // }
    var ins = new OrdinalMeta({
      categories: categories,
      needCollect: !categories,
      extraCategory: extraCategory,
      // deduplication is default in axis.
      deduplication: option.dedplication !== false,
      loadMoreCategory: option.loadMoreCategory,
      // timePoints,
      marksByWeight: marksByWeight,
      dataInterval: option.dataInterval,
      utcOffsetTime: option.utcOffsetTime
    });
    // console.log('%c [ windowId ]-123', 'font-size:13px; background:pink; color:#bf2c9f;', windowId)
    // if (windowId) {
    //     ordinalMetaInstanceById[windowId] = ins
    // }
    return ins;
  };
  ;
  OrdinalMeta.prototype.getOrdinal = function (category) {
    // @ts-ignore
    return this._getOrCreateMap().get(category);
  };
  OrdinalMeta.prototype.getMarksByWeight = function () {
    return this._marksByWeight;
  };
  OrdinalMeta.prototype.reFillExtraCategories = function (startTime) {
    var timePoints = [];
    var marksByWeight = new HashMap();
    var formatInterval = this.dataInterval === '1D';
    var utcOffsetTime = this.utcOffsetTime;
    var addItem = function (value, index) {
      var d = formatInterval ? convertToUTCDayStart(value - utcOffsetTime) : value * 1000;
      timePoints.push({
        originalTime: value,
        index: index,
        timestamp: d / 1000
      });
    };
    var categories = this.categories;
    each(categories, function (val, index) {
      addItem(val, index);
    });
    var extraCategory = this.loadMoreCategory(startTime, 300);
    map(extraCategory, function (val, i) {
      var index = i + categories.length;
      addItem(val, index);
    });
    if (timePoints.length) {
      fillWeightsForPoints(timePoints);
      for (var index = 0; index < timePoints.length; ++index) {
        var point = timePoints[index];
        var marksForWeight = marksByWeight.get(point.weight);
        if (marksForWeight === undefined) {
          marksForWeight = [];
          marksByWeight.set(point.weight, marksForWeight);
        }
        marksForWeight.push(point);
      }
    }
    this.extraCategory = extraCategory;
    this._marksByWeight = marksByWeight;
    this._appendCount = 0;
    this.cache = null;
  };
  OrdinalMeta.prototype.appendData = function (data) {
    var _a;
    var _this = this;
    if (this._map) {
      var length_1 = this.categories.length;
      each(data, function (item, index) {
        _this._map.set(getName(item), length_1 + index);
      });
    }
    (_a = this.categories).push.apply(_a, data);
    var lastUpdateTime = +data[data.length - 1];
    if (lastUpdateTime !== +this.extraCategory[0]) {
      this.reFillExtraCategories(lastUpdateTime);
      return;
    }
    this.extraCategory.splice(0, data.length);
    if (this.loadMoreCategory) {
      var startTime = this.extraCategory[this.extraCategory.length - 1];
      var moreCategory = this.loadMoreCategory(startTime, data.length);
      var utcOffsetTime_1 = this.utcOffsetTime;
      var formatInterval_1 = this.dataInterval === '1D';
      moreCategory.unshift(startTime);
      var timePoints_1 = [];
      var startIndex_1 = this.categories.length + this.extraCategory.length - 1;
      each(moreCategory, function (val, index) {
        if (index) {
          _this.extraCategory.push(getName(val));
        }
        timePoints_1.push({
          originalTime: val,
          index: index + startIndex_1,
          timestamp: formatInterval_1 ? convertToUTCDayStart(val - utcOffsetTime_1) / 1000 : val
        });
      });
      var marksByWeight = this._marksByWeight;
      fillWeightsForPoints(timePoints_1);
      for (var index = 0; index < timePoints_1.length; ++index) {
        if (index === 0) {
          continue;
        }
        var point = timePoints_1[index];
        var marksForWeight = marksByWeight.get(point.weight);
        if (marksForWeight === undefined) {
          marksForWeight = [];
          marksByWeight.set(point.weight, marksForWeight);
        }
        marksForWeight.push(point);
      }
    }
    this._appendCount = this._appendCount + 1;
    // 新增一定的条数重新生成缓存
    if (this._appendCount > 100) {
      this._appendCount = 0;
      this.cache = null;
    }
  };
  OrdinalMeta.prototype.getCategories = function () {
    return this.categories;
  };
  OrdinalMeta.prototype.getClosestTime = function (time) {
    var findTime = findClosestTimestamp(this.categories, time);
    return this.getOrdinal(findTime);
  };
  OrdinalMeta.prototype.getLastCategories = function () {
    return this.categories[this.categories.length - 1];
  };
  OrdinalMeta.prototype.getCategoriesSize = function () {
    return this.categories.length;
  };
  /**
   * @return The ordinal. If not found, return NaN.
   */
  OrdinalMeta.prototype.parseAndCollect = function (category) {
    var index;
    var needCollect = this._needCollect;
    // The value of category dim can be the index of the given category set.
    // This feature is only supported when !needCollect, because we should
    // consider a common case: a value is 2017, which is a number but is
    // expected to be tread as a category. This case usually happen in dataset,
    // where it happent to be no need of the index feature.
    if (!isString(category) && !needCollect) {
      return category;
    }
    // Optimize for the scenario:
    // category is ['2012-01-01', '2012-01-02', ...], where the input
    // data has been ensured not duplicate and is large data.
    // Notice, if a dataset dimension provide categroies, usually echarts
    // should remove duplication except user tell echarts dont do that
    // (set axis.deduplication = false), because echarts do not know whether
    // the values in the category dimension has duplication (consider the
    // parallel-aqi example)
    if (needCollect && !this._deduplication) {
      index = this.categories.length;
      this.categories[index] = category;
      return index;
    }
    var map = this._getOrCreateMap();
    // @ts-ignore
    index = map.get(category);
    if (index == null) {
      if (needCollect) {
        index = this.categories.length;
        this.categories[index] = category;
        // @ts-ignore
        map.set(category, index);
      } else {
        index = NaN;
      }
    }
    return index;
  };
  OrdinalMeta.prototype.parseAndExtra = function (category) {
    var index;
    var needCollect = this._needCollect;
    if (!isString(category) && !needCollect) {
      return category;
    }
    var map = this._getOrCreateMap();
    // @ts-ignore
    index = map.get(category);
    if (index == null) {
      var idx = findClosestIndex(this.extraCategory, category);
      return ~idx ? this.categories.length + idx : NaN;
    }
    return index;
  };
  // Consider big data, do not create map until needed.
  OrdinalMeta.prototype._getOrCreateMap = function () {
    return this._map || (this._map = createHashMap(this.categories));
  };
  return OrdinalMeta;
}();
function getName(obj) {
  if (isObject(obj) && obj.value != null) {
    return obj.value;
  } else {
    return obj + '';
  }
}
export default OrdinalMeta;