import process from 'process';

/**
 * @deprecated use `ServiceState` instead
 */
export class RequestState {
  loading: boolean;
  success: boolean;
  constructor() {
    this.loading = true;
    this.success = false;
  }
}

/**
 * Service state machine
 *
 * @example
 * let former = that.state.service;
 * that.setState({
 *   service: former.trans(true),
 * })
 *
 */
export class ServiceState {
  private state: 'loading' | 'success' | 'failed';

  constructor() {
    this.state = 'loading';
  }

  /**
   * Transist from `loading` to `success` or `failed`
   * @param success request succeeded or not
   */
  trans(success: boolean) {
    if (this.state == 'loading') {
      if (success) {
        this.state = 'success';
      } else {
        this.state = 'failed';
      }
    }
  }

  /**
   * Check if state is `loading`.
   * @returns in `loading` state or not.
   */
  isLoading(): boolean {
    return this.state == 'loading';
  }

  /**
   * Check if state is `success`.
   * @returns in `success state or not.
   */
  isSuccess(): boolean {
    return this.state == 'success';
  }

  /**
   * Check if state is `failed`.
   * @returns in `failed` state or not.
   */
  isFailed(): boolean {
    return this.state == 'failed';
  }
}

/**
 * Get URL of backend
 * @param path Relative path to base url, begins with `/`
 * @returns Full url
 *
 * @example
 *
 * ``` tsx
 * import { getUrl } from '@/service';
 * import { Component, ReactNode } from 'react';
 * import Taro from '@tarojs/taro';
 *
 * class Index extends Component {
 *   state = {
 *     testData: {},
 *   }
 *   componentDidMount(): void {
 *    Taro.request({
 *      url: getUrl('/testdata'),
 *      method: 'GET',
 *    }).then(res => {
 *      console.log(res.data);
 *      this.setState({ testData: res.data.data });
 *    });
 *  }
 *  render() { ... }
 * }
 * ```
 */
export function getUrl(path: string): string {
  const baseUrl = process.env.TARO_APP_API;
  // console.log('bu:', baseUrl);
  if (baseUrl) {
    return baseUrl + path;
  } else {
    console.log('env TARO_APP_API is undefined');
    return '';
  }
}
