import Taro from '@tarojs/taro';

export default function getAuthorize(scope) {
  return new Promise((resolve, reject) => {
    Taro.getSetting({
      success(res) {
        if (!res.authSetting[scope]) {
          Taro.authorize({
            scope,
            success: resolve,
            fail: (err) => {
              console.error(err);
              reject(err);
            },
          })
        } else {
          resolve();
        }
      },
      fail(err) {
        console.error(err);
        reject(err);
      }
    });
  });
}

export const getLocation = (options) => {
  return new Promise((resolve, reject) => {
    getAuthorize('scope.userLocation').then(() => {
      Taro.getLocation({
        ...options || {},
        success(res) {
          resolve(res);
        },
        fail(err) {
          console.error(err);
          reject(err);
        }
      });
    }).catch((err) => {
      console.error(err);
      reject(err);
    });
  });
}
