//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { reqPath } from '@/api/reqPath';
import $http from '@/utils/http-service';
import { mapReauth } from '@/utils/sensitive';

// 获取VNC数据
export function getVncData() {
  return new Promise((resolve, reject) => {
    $http
      .get(reqPath.vnc.getVncData)
      .then((res: any) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        reject(err);
      }).finally(() => {
        resolve(null);
      });
  });
}

// 编辑VNC数据
export function editVncData(params: any) {
  return new Promise((resolve, reject) => {
    $http
      .patch(reqPath.vnc.getVncData, params)
      .then((res: any) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}

function setVnc(params: any) {
  return new Promise((resolve, reject) => {
    if (JSON.stringify(params) !== '{}') {
      $http
        .patch(reqPath.vnc.getVncData, params)
        .then(res => {
          resolve(res);
        })
        .catch((err: any) => {
          reject(err);
        });
    } else {
      resolve(false);
    }
  });
}

function setVncPwdWithoutPassword(params: any) {
  return new Promise((resolve, reject) => {
    $http
      .patch(reqPath.vnc.password, params)
      .then(res => {
        resolve(res);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}

// 编辑VNC数据
export function setVncListWithoutPassword(params: any, vncPwd: any) {
  return new Promise((resolve, reject) => {
    Promise.all([setVncPwdWithoutPassword(vncPwd), setVnc(params)])
      .then(resArr => {
        resolve(resArr);
      })
      .catch(error => {
        reject(error);
      });
  });
}

function setVncPwd(params: any, pwd: string) {
  return new Promise((resolve, reject) => {
    if (pwd !== '') {
      params.ReauthKey = window.btoa(pwd);
      mapReauth(['VNCPassword'])(params)
        .patch(reqPath.vnc.password, params)
        .then(res => {
          resolve(res);
        })
        .catch((err: any) => {
          reject(err);
        });
    } else {
      resolve(false);
    }
  });
}

// 编辑VNC数据
export function setVncList(params: any, vncPwd: any, pwd: string): Promise<any> {
  return new Promise((resolve, reject) => {
    Promise.all([setVncPwd(vncPwd, pwd), setVnc(params)])
      .then(resArr => {
        resolve(resArr);
      })
      .catch(error => {
        reject(error);
      });
  });
}
