'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var pixui_gamelet = require('./gamelet.js');

// 定位 flag，标记定位返回结果的类型
exports.LocationFlagInPixui = void 0;
(function (LocationFlagInPixui) {
  LocationFlagInPixui[LocationFlagInPixui["LocationSuccess"] = 1] = "LocationSuccess";
  LocationFlagInPixui[LocationFlagInPixui["LocationNoPermission"] = 2] = "LocationNoPermission";
  LocationFlagInPixui[LocationFlagInPixui["LocationFailed"] = 3] = "LocationFailed";
})(exports.LocationFlagInPixui || (exports.LocationFlagInPixui = {}));
/**
 * 获取游戏定位信息,回调数据
 * {
 *   flag: LocationFlagInPixui,
 *   lat: number,
 *   lng: number,
 * }
 * @example
 * ```ts
 * const res = await getLocationInPixui(platformAPI);
 * if (res.flag === LocationFlagInPixui.LocationSuccess) {
 *   console.log('lat:', res.lat, 'lng:', res.lng);
 * } else if (res.flag === LocationFlagInPixui.LocationNoPermission) {
 *   console.log('未开启系统定位权限');
 * }
 * ```
 */
var getLocationInPixui = function getLocationInPixui(platformAPI) {
  return new Promise(function (resolve) {
    var _onGameCommandListener = function onGameCommandListener(message) {
      try {
        var data = JSON.parse(message);
        if (data.type === 'updateLocation') {
          if (data.longitude == 0 && data.latitude == 0) {
            // 游戏返回的经纬度值均为 0，则表示用户 GPS 系统开关未打开
            resolve({
              flag: exports.LocationFlagInPixui.LocationNoPermission,
              lat: 0,
              lng: 0
            });
          } else {
            resolve({
              flag: exports.LocationFlagInPixui.LocationSuccess,
              lat: +data.latitude,
              lng: +data.longitude
            });
          }
          // 去除监听
          pixui_gamelet.getGameletPixuiFrame().GameletAPI.removeOnGameCommandListener(_onGameCommandListener);
        }
      } catch (e) {
        console.error(e);
      }
    };
    // 监听游戏回调地图信息
    pixui_gamelet.getGameletPixuiFrame().GameletAPI.addOnGameCommandListener(_onGameCommandListener);
    platformAPI.callGame(JSON.stringify({
      type: 'checkLocation',
      content: '1'
    }));
  });
};

exports.getLocationInPixui = getLocationInPixui;
