/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { common } from '@kit.AbilityKit';
import Constants from '../../common/constants/constant';
import { HiLog } from '../../common/base/HiLog';
import { isValidPath } from '../../common/FileUtils/utils';
import Result from '../../common/base/Result';
import { ResultMsg } from '../../common/base/ResultMsg';

const TAG: string = 'StartFileManager';

export class StartFileManager {
  public static async startFileManager(uri: string | undefined): Promise<Result<void>> {
    const context: common.ServiceExtensionContext | undefined = AppStorage.get('viewContext');
    if (!context) {
      HiLog.error(TAG, 'startFileManager viewContext is null.');
      return ResultMsg.getErrMsg(Constants.ERR_JS_APP_PARAM_ERROR);
    }
    if (!uri || !isValidPath(uri)) {
      HiLog.error(TAG, 'startFileManager uri is invalid.');
      return ResultMsg.getErrMsg(Constants.ERR_JS_APP_PARAM_ERROR);
    }
    const viewContext = context as common.ServiceExtensionContext;
    try {
      await viewContext.openLink(Constants.OPEN_DIRECTORY_LINK, {
        appLinkingOnly: false,
        parameters: {
          'fileUri': uri
        }
      })
      return ResultMsg.buildSuccess();
    } catch (error) {
      HiLog.wrapError(TAG, error, 'openLink error');
      return ResultMsg.getErrMsg(Constants.ERR_JS_APP_PARAM_ERROR);
    }
  }
}