import { AgoraFetch } from "../utils/fetch";
import jwt_decode from 'jwt-decode';
import {roomStore} from "../stores/room";
import GlobalStorage from "../utils/custom-storage";

const ENDPOINT: string = process.env.REACT_APP_AGORA_ENDPOINT as string;

const AUTHORIZATION_KEY: string = process.env.REACT_APP_AGORA_ENDPOINT_AK as string;

const AgoraFetchJson = async ({url, method, data, token}:{url: string, method: string, data?: any, token?: string}) => {
  const opts: any = {
    method,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': AUTHORIZATION_KEY
    }
  }

  if (data) {
    opts.body = JSON.stringify(data);
  }

  if (token) {
    opts.token = token;
  }

  let resp = await AgoraFetch(`${url}`, opts);
  return resp.json();
}

export interface EntryParams {
  userName: string
  roomName: string
  type: number
  role: number
}

export interface RoomParams {
  muteAllChat: boolean
  userId: number
  enableChat: number
  enableVideo: number
  enableAudio: number
  linkUsers: number[]
}

export function goHome(history: any){
  GlobalStorage.clear('agora_room');
  window.onbeforeunload = null;
  window.location.href = 'http://iteachabc.com'
}
export function goLogin(){
  window.location.href = 'http://iteachabc.com/manage/login'
}
export function getApiServerHost(online = false) {
  // return 'http://127.0.0.1:1339'
  let host = `https://ac.iplayabc.com`;
  if (window.location.host.includes('s-live.')) {
    host = 'https://staging-ac.ireadabc.com';
  } else if (window.location.host.includes('127.0.0.1')
    || window.location.host.includes('localhost')) {
    if (online) {
      host = 'https://staging-ac.ireadabc.com';
    } else {
      host = 'http://127.0.0.1:1338'
    }

  }
  return host;
}
export function getTeachServerHost() {
  let host = `https://teach.ireadabc.com`;
  if (window.location.host.includes('s-live.')) {
    host = 'https://staging-teach.ireadabc.com';
  } else if (window.location.host.includes('127.0.0.1')
    || window.location.host.includes('localhost')) {
    host = 'http://127.0.0.1:1338'
  }
  return host;
}
export class EndPoint {

  appID: string = '';
  roomId: string = '';
  userToken: string = '';
  recordId: string = '';
  setUserToken(token: string) {
    this.userToken = token
  }
  async sts () {
    let response = await AgoraFetch(`https://omt.iplayabc.com/api/oss/live/static`, {
      method: 'GET',
    });
    let json = await response.json();
    return json.data;
  }
  async fetchClasses(username: string) {
    const host = getApiServerHost(true);
    let url = `${host}/api/classes?username=${username}`;
    let json = await AgoraFetchJson({
      url: url,
      method: 'GET'
    });
    if(json.msg==="error"){
      throw json.data;
    }
    console.log('json.data', json.data);
    if (json.data && json.data.length) {
      return json.data
    }
    return [];
  }

  async login(data: any, local=false) {
    if (local) {
      const info = {
        id: `${data.username}`,
        class_id: `${data.classid}`,
        classRole: (`${data.username}`==="1" || `${data.username}`==="11")?"tea":"",
        roomType: 1,
        nick_name: `${data.username}`,
        // data.username: session.yourName,
        // data.password: session.yourPass
      }
      if (data.username.startsWith('dev')) {
        info.classRole = 'developer'
      }
      return info;
    }
    const host = getApiServerHost(true);
    let url = `${host}/api/login`;
    let json = await AgoraFetchJson({
      url: url,
      method: 'POST',
      data: data
    });
    if(json.msg==="error"){
      throw json.data;
    }
    let token = json.data;
    this.userToken = token;
    try {
      let userInfo = jwt_decode(token);
      return userInfo;
    } catch (Error) {
      return null;
    }
  }

  getUserInfo(){
    try {
      let userInfo = jwt_decode(this.userToken);
      return userInfo;
    } catch (Error) {
      return null;
    }
  }

  getCourseUrl(){
    if (!this.userToken) {
      this.userToken = roomStore.state.cwLink;
    }
    console.log('getCourseUrl', this.userToken)
    const host = getApiServerHost(true);
    return `${host}/airclass_ol?token=${this.userToken}`;
  }

  async config() {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/room/config`,
      method: 'GET',
    });
    this.appID = json.data.appId;
    return {
      code: json.code,
      appId: json.data.appId,
      room: json.data.room,
    }
  }

  /**
   * entry
   * @param params {@link EntryParams}
   */
  async entry(params: EntryParams) {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/entry`,
      method: 'POST',
      data: params
    });

    this.roomId = json.data.room.roomId;
    this.userToken = json.data.user.userToken;
    return {
      code: json.code,
      msg: json.msg,
      data: json.data,
    }
  }

  /**
   * refreshToken
   */
  async refreshToken() {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}/token/refresh`,
      method: 'POST',
      token: this.userToken,
    });
    return {
      code: json.code,
      msg: json.msg,
      data: json.data
    }
  }

  /**
   * updateRoom
   * @param params
   */
  async updateRoom(params: RoomParams) {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}`,
      method: 'POST',
      data: params,
      token: this.userToken,
    });
    return {
      code: json.code,
      msg: json.msg,
      data: json.data
    }
  }

  /**
   * start recording
   */
  async startRecording() {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}/record`,
      method: 'POST',
      token: this.userToken,
    });
    this.recordId = json.data;
    return {
      code: json.code,
      data: json.data,
      msg: json.msg
    }
  }

  /**
   * stop recording
   */
  async stopRecording() {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}/${this.recordId}/stop`,
      method: 'POST',
      token: this.userToken,
    })
    return {
      code: json.code,
      data: json.data,
      msg: json.msg
    }
  }

  /**
   * get recording list
   */
  async getRecordingList () {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}/records`,
      method: 'GET'
    })
    return {
      code: json.code,
      data: json.data,
      msg: json.msg,
    }
  }

  /**
   * getRoomInfo
   */
  async getRoomInfoBy() {
    let json = await AgoraFetchJson({
      url: `${ENDPOINT}/v1/apps/${this.appID}/room/${this.roomId}`,
      method: 'GET',
    });
    return {
      code: json.code,
      msg: json.msg,
      data: json.data
    }
  }

}

export const endPoint = new EndPoint();
// @ts-ignore
window.endPoint = endPoint;
