//  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 $http from '@/utils/http-service';
import {
  ILdap,
  ILdapCertificate,
  ILdapController,
  ILdapState,
  ILdapUserGroup,
} from '@/model/Users/ldap-interface';
import { IResponse } from '@/model/base-interface';
import { transformRole } from '@/utils/utils';
import { LdapController } from '../model/controller';
import { LdapCertificate } from '../model/certificate';
import { LdapGroup } from '../model/group';
import { getStoreData } from '@/utils/composition';
import { UI_REST_FIRMWAREINVENTORY } from '@/api/api';
import { mapReauth, reauthHandler } from '@/utils/sensitive';

// 获取LDAP使能
export function getLdapState(): Promise<ILdapState> {
  return new Promise((resolve, reject) => {
    $http.get('/UI/Rest/AccessMgnt/LDAP').then((res: IResponse) => {
      const data: ILdapState = res.data as ILdapState;
      resolve(data);
    });
  });
}

export function setLdapState(state: boolean): Promise<any> {
  return $http.patch('/UI/Rest/AccessMgnt/LDAP', { Enabled: state });
}

// 获取LDAP控制器信息
export function getLdapControls(ctrlId: string): Promise<any> {
  return new Promise((resolve, reject) => {
    $http.get(`/UI/Rest/AccessMgnt/LDAP/${ctrlId}`).then(
      (res: IResponse) => {
        if (res?.data) {
          const { Controller, Certificate, LdapGroup: ldapGp } = res.data;
          const controller: any = Controller ? createControl(Controller) : {};
          const certData: any = Certificate ? createCert(Certificate) : {};
          const groups: any = ldapGp?.Members ? createGroup(ldapGp.Members) : [];
          const data: ILdap = {
            Controller: controller,
            LdapGroup: groups,
            Certificate: certData,
          };
          resolve(data);
        } else {
          resolve({
            Controller: {},
            LdapGroup: {},
            Certificate: [],
          });
        }
      },
      (error: Error) => {
        reject(error);
      },
    );
  });
}

function createControl(dataCtrl: ILdapController) {
  return new LdapController({
    address: dataCtrl.IPAddress,
    port: dataCtrl.Port,
    domain: dataCtrl.Domain,
    bindDN: dataCtrl.BindDN,
    folder: dataCtrl.Folder,
  });
}

function createCert(dataCert: ILdapCertificate) {
  return new LdapCertificate({
    rootCert: dataCert.RootCert,
    serverCert: dataCert.ServerCert,
    intermediateCert: dataCert.IntermediateCert,
    crlState: dataCert.CrlVerification,
    certEnabled: dataCert.VerificationEnabled,
    certLevel: dataCert.VerificationLevel,
  });
}

function createGroup(userGroups: ILdapUserGroup[]) {
  const groups: ILdapUserGroup[] = [];
  userGroups.forEach((item: ILdapUserGroup, index: number) => {
    const group = new LdapGroup({
      id: item.ID,
      name: item.Name,
      roleID: item.RoleID,
      roleLabel: transformRole(item.RoleID),
      folder: item.Folder,
      loginInterface: item.LoginInterface,
      loginRule: item.LoginRule,
    });
    groups.push(group);
  });
  return groups;
}

// 保存LDAP基础配置属性
export function saveLdap(rul: string, param: { [key: string]: any }, pwd: string): Promise<any> {
  const isNoPwd = getStoreData('loct', 'nopwd');
  if (!isNoPwd && pwd !== '') {
    param.ReauthKey = window.btoa(pwd);
  }
  const bindPwdPath = param.Controller?.BindPwd ? [['Controller', 'BindPwd']] : [];
  return mapReauth(bindPwdPath)(param).patch(rul, param);
}

// 删除LDAP用户组
export function saveLdapGroup(url: string, param: any, pwd: string) {
  const isNoPwd = getStoreData('loct', 'nopwd');
  if (!isNoPwd && pwd !== '') {
    param.ReauthKey = window.btoa(pwd);
  }
  return reauthHandler(param).patch(url, param);
}

// 上传LDAP证书文件
export function uploadLdapFile(formData: FormData) {
  return $http.post(UI_REST_FIRMWAREINVENTORY, formData);
}

export function importLdapFile(url: string, fileName: string, password: string) {
  const data = { Content: `/tmp/web/${fileName}` };
  return $http.post(url, data);
}
