/*
 * Copyright (C) 2021-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.
 */

#ifndef CALL_CONTROL_MANAGER_H
#define CALL_CONTROL_MANAGER_H

#include <cstring>
#include <list>
#include <memory>


#include "app_state_observer.h"
#include "call_broadcast_subscriber.h"
#include "call_policy.h"
#include "call_request_handler.h"
#include "call_setting_manager.h"
#include "call_state_listener.h"
#include "incoming_call_wake_up.h"
#include "missed_call_notification.h"
#include "pac_map.h"
#include "singleton.h"
#include "system_ability_status_change_stub.h"
#include "ffrt.h"

#ifdef ABILITY_POWER_SUPPORT
#include "power_mgr_client.h"
#endif
#ifdef SUPPORT_RTT_CALL
#include "rtt_call_listener.h"
#endif

/**
 * Singleton
 * @ClassName:CallControlManager
 * @Description:CallControlManager is designed for performing dial/answer/reject etc ops
 * on kinds of calls(ims,cs,ott). usually as an entrance for downflowed [app->ril] telephony business
 */
namespace OHOS {
namespace Telephony {
    constexpr const char *KEY_CONST_TELEPHONY_READ_SET_VOIP_CALL_INFO =
        "const.telephony.read_set_voip_call_info";
    constexpr int32_t WEAR_STATUS_INVALID = 0;
    constexpr int32_t WEAR_STATUS_OFF = 1;
    constexpr int32_t WEAR_STATUS_ON = 2;
    constexpr int32_t DROP_CALL_BY_THERMAL_PROTECTION = 1;
    constexpr int32_t DROP_CALL_BY_WATCH_CALL_BLOCKING = DROP_CALL_BY_THERMAL_PROTECTION + 1;
    constexpr int32_t DROP_CALL_BY_POWER_OFF = DROP_CALL_BY_WATCH_CALL_BLOCKING + 1;
    constexpr int32_t DROP_CALL_BY_MULTI_CALL_REJECT = DROP_CALL_BY_POWER_OFF + 1;
    constexpr int32_t DROP_CALL_BY_EXTERNAL_INVOCATION = DROP_CALL_BY_MULTI_CALL_REJECT + 1;
    constexpr int32_t DROP_CALL_BY_EMC_CALL_EXIST = DROP_CALL_BY_EXTERNAL_INVOCATION + 1;
    constexpr int32_t DROP_CALL_BY_INVALID_DEVICE_PROPERTY = DROP_CALL_BY_EMC_CALL_EXIST + 1;
    constexpr int32_t DROP_CALL_BY_OOBE = DROP_CALL_BY_INVALID_DEVICE_PROPERTY + 1;
    constexpr int32_t DROP_CALL_BY_FOCUS_MODE = DROP_CALL_BY_OOBE + 1;
    constexpr int32_t DROP_CALL_BY_CALL_BLOCKING = DROP_CALL_BY_FOCUS_MODE + 1;
    constexpr int32_t DROP_CALL_BY_VOIP_CONFLICT = DROP_CALL_BY_CALL_BLOCKING + 1;
    constexpr int32_t DROP_CALL_BY_MEETIME_CONFLICT = DROP_CALL_BY_VOIP_CONFLICT + 1;
    constexpr int32_t DROP_CALL_BY_CALL_NUM_LIMITED = DROP_CALL_BY_MEETIME_CONFLICT + 1;
    constexpr int32_t DROP_CALL_BY_MEETIME_CALL_ALERTING = DROP_CALL_BY_CALL_NUM_LIMITED + 1;
class WearStatusObserver : public AAFwk::DataAbilityObserverStub {
public:
    WearStatusObserver() = default;
    ~WearStatusObserver() = default;
    void OnChange() override;
};
class IncomingFlashReminder;
class CallControlManager : public CallPolicy, public std::enable_shared_from_this<CallControlManager> {
    DECLARE_DELAYED_SINGLETON(CallControlManager)

public:
    bool Init();
    void UnInit();
    int32_t DialCall(std::u16string &number, AppExecFwk::PacMap &extras);
    int32_t AnswerCall(int32_t callId, int32_t videoState, bool isRTT = false);
    int32_t HandlerAnswerCall(int32_t callId, int32_t videoState, bool isRTT = false);
    int32_t RejectCall(int32_t callId, bool rejectWithMessage, std::u16string textMessage);
    int32_t HangUpCall(int32_t callId);
    int32_t GetCallState();
    int32_t HoldCall(int32_t callId);
    int32_t UnHoldCall(int32_t callId);
    int32_t SwitchCall(int32_t callId);
    bool HasCall();
    bool HasVoipCall();
    int32_t GetMeetimeCallState();
    int32_t IsNewCallAllowed(bool &enabled);
    int32_t IsRinging(bool &enabled);
    int32_t HasEmergency(bool &enabled);
    bool NotifyNewCallCreated(sptr<CallBase> &callObjectPtr);
    bool NotifyCallDestroyed(const DisconnectedDetails &details);
    bool NotifyCallStateUpdated(sptr<CallBase> &callObjectPtr, TelCallState priorState, TelCallState nextState);
    bool NotifyVoipCallStateUpdated(CallAttributeInfo info, TelCallState priorState, TelCallState nextState);
    bool NotifyIncomingCallAnswered(sptr<CallBase> &callObjectPtr);
    bool NotifyIncomingCallRejected(sptr<CallBase> &callObjectPtr, bool isSendSms, std::string content);
    bool NotifyCallEventUpdated(CallEventInfo &info);
    int32_t StartDtmf(int32_t callId, char str);
    int32_t StopDtmf(int32_t callId);
    int32_t PostDialProceed(int32_t callId, bool proceed);
    int32_t GetCallWaiting(int32_t slotId);
    int32_t SetCallWaiting(int32_t slotId, bool activate);
    int32_t GetCallRestriction(int32_t slotId, CallRestrictionType type);
    int32_t SetCallRestriction(int32_t slotId, CallRestrictionInfo &info);
    int32_t SetCallRestrictionPassword(
        int32_t slotId, CallRestrictionType fac, const char *oldPassword, const char *newPassword);
    int32_t GetCallTransferInfo(int32_t slotId, CallTransferType type);
    int32_t SetCallTransferInfo(int32_t slotId, CallTransferInfo &info);
    int32_t CanSetCallTransferTime(int32_t slotId, bool &result);
    int32_t SetCallPreferenceMode(int32_t slotId, int32_t mode);
    // merge calls
    int32_t CombineConference(int32_t mainCallId);
    int32_t SeparateConference(int32_t callId);
    int32_t KickOutFromConference(int32_t callId);
    int32_t GetMainCallId(int32_t callId, int32_t &mainCallId);
    int32_t GetSubCallIdList(int32_t callId, std::vector<std::u16string> &callIdList);
    int32_t GetCallIdListForConference(int32_t callId, std::vector<std::u16string> &callIdList);
    int32_t GetImsConfig(int32_t slotId, ImsConfigItem item);
    int32_t SetImsConfig(int32_t slotId, ImsConfigItem item, std::u16string &value);
    int32_t GetImsFeatureValue(int32_t slotId, FeatureType type);
    int32_t SetImsFeatureValue(int32_t slotId, FeatureType type, int32_t value);
    int32_t EnableImsSwitch(int32_t slotId);
    int32_t DisableImsSwitch(int32_t slotId);
    int32_t IsImsSwitchEnabled(int32_t slotId, bool &enabled);
    int32_t SetVoNRState(int32_t slotId, int32_t state);
    int32_t GetVoNRState(int32_t slotId, int32_t &state);
    int32_t UpdateImsCallMode(int32_t callId, ImsCallMode mode);
    void RemovePendingHangupProtectTask();
#ifdef SUPPORT_RTT_CALL
    int32_t SetRttCapability(int32_t slotId, bool isEnable);
    int32_t UpdateImsRttCallMode(int32_t callId, ImsRTTCallMode mode);
    int32_t UnInitRttManager();
    void RefreshRttManager(const CallDetailInfo &callInfo);
    int32_t SendRttMessage(const std::string &rttMessage);
#endif
    // invite calls to participate conference
    int32_t JoinConference(int32_t callId, std::vector<std::u16string> &numberList);
    int32_t SetMuted(bool isMute);
    int32_t MuteRinger();
    int32_t SetAudioDevice(const AudioDevice &audioDevice);
    int32_t ControlCamera(std::u16string cameraId, int32_t callingUid, int32_t callingPid);
    int32_t SetPreviewWindow(VideoWindow &window);
    int32_t SetDisplayWindow(VideoWindow &window);
    int32_t SetCameraZoom(float zoomRatio);
    int32_t SetPausePicture(std::u16string path);
    int32_t SetDeviceDirection(int32_t rotation);
    int32_t IsEmergencyPhoneNumber(std::u16string &number, int32_t slotId, bool &enabled);
    int32_t FormatPhoneNumber(std::u16string &number, std::u16string &countryCode, std::u16string &formatNumber);
    int32_t FormatPhoneNumberToE164(
        std::u16string &number, std::u16string &countryCode, std::u16string &formatNumber);
    int32_t CloseUnFinishedUssd(int32_t slotId);
    void GetDialParaInfo(DialParaInfo &info);
    void GetDialParaInfo(DialParaInfo &info, AppExecFwk::PacMap &extras);
    void ConnectCallUiService(bool shouldConnect);
    void SetReduceRingToneVolume(bool reduceRingToneVolume);
    bool GetReduceRingToneVolume();
    bool ShouldDisconnectService();
    int32_t RemoveMissedIncomingCallNotification();
    int32_t SetVoIPCallState(int32_t state);
    int32_t GetVoIPCallState(int32_t &state);
    int32_t SetVoIPCallInfo(int32_t callId, int32_t state, std::string phoneNumber);
    int32_t GetVoIPCallInfo(int32_t &callId, int32_t &state, std::string &phoneNumber);
    int32_t AddCallLogAndNotification(sptr<CallBase> &callObjectPtr);
    int32_t AddBlockLogAndNotification(sptr<CallBase> &callObjectPtr);
    int32_t HangUpVoipCall();
    int32_t CarrierAndVoipConflictProcess(int32_t callId, TelCallState callState);
    void AcquireIncomingLock();
    void ReleaseIncomingLock();
    void AcquireDisconnectedLock();
    void ReleaseDisconnectedLock();
    void DisconnectAllCalls(bool isIncludeEmergencyCall = true,
        bool isFromThermalProtection = false, bool isWaitingForResponse = true);
    void StartFlashRemind();
    void SetRegMmiCodeCallbackState(bool isReg);
    void StopFlashRemind();
    void ClearFlashReminder();
    bool SetVirtualCall(bool isVirtual);
#ifdef NOT_SUPPORT_MULTICALL
    bool HangUpOtherCall(int32_t answerCallId);
    void HangUpOtherCallByAnswerCallID(int32_t answerCallId, bool autoAnswerState = false);
#endif
    bool IsNotWearOnWrist();
    void SetWearState(int32_t state);
    void RegisterObserver();
    void UnRegisterObserver();
    void HandleVideoRingPlayFail();
    void PreloadCallUi(bool enable, int32_t callingPid);
    bool EndCall();
    int32_t SetCallAudioMode(int32_t mode, int32_t scenarios);
#ifdef CALL_MANAGER_THERMAL_PROTECTION
    void HandleThermalLevelChange(int32_t level);
    bool IsThermalProtectionRequired();
    bool IsEmergencyCall(const sptr<CallBase> &call);
#endif

private:
    void CallStateObserve();
    int32_t NumberLegalityCheck(std::string &number);
    int32_t SubscriberSaStateChange();
    void ReportPhoneUEInSuperPrivacy(const std::string &eventName);
    void PackageDialInformation(AppExecFwk::PacMap &extras, std::string accountNumber, bool isEcc);
    static void handler();
    bool cancel(ffrt::task_handle &handle);
    int32_t CanDial(std::u16string &number, AppExecFwk::PacMap &extras, bool isEcc);
    void AnswerHandlerForSatelliteOrVideoCall(sptr<CallBase> &call, int32_t videoState);
    bool CurrentIsSuperPrivacyMode(int32_t callId, int32_t videoState);
    void RegisterAppStateObserver();
    void UnregisterAppStateObserver();
    void SetCallTypeExtras(AppExecFwk::PacMap &extras);
    void HandleVoipConnected(int32_t &numActive, int32_t callId);
    void HandleVoipDialing(int32_t callId, const std::string &phoneNumber);
    void HandleVoipAlerting(int32_t callId, const std::string &phoneNumber);
    void HandleVoipIncoming(int32_t &numActive, int32_t callId, const std::string &phoneNumber);
    int32_t HandleVoipDisconnected(int32_t &numActive, int32_t numHeld, int32_t callId,
        int32_t state, const std::string &phoneNumber);
    bool IsSupportSetVoipInfo();
    void SetVoipCallInfoInner(const int32_t callId, const int32_t state,
        const std::string phoneNumber);
    void sendEventToVoip(CallAbilityEventId eventId);
    bool IsCallActivated(const TelCallState& priorState, const TelCallState& nextState);
    void EnqueueAnsweredCall(int32_t callId, int32_t videoState);
    sptr<CallBase> GetRingCall(int32_t callId, int32_t videoState);
    void PostPendingHangupProtectTask(int32_t callId);
private:
    class SystemAbilityListener : public SystemAbilityStatusChangeStub {
    public:
        explicit SystemAbilityListener();
        ~SystemAbilityListener() = default;
        void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
        void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;

    private:
        void CommonBroadcastSubscriber();
        void NearlinkBroadcastSubscriber();
        void ContactsBroadcastSubscriber();
        void SatcommBroadcastSubscriber();
        void SuperPrivacyModeBroadcastSubscriber();
        void HSDRBroadcastSubscriber();
        void HfpBroadcastSubscriber();
        void MuteKeyBroadcastSubscriber();
        void TelephonyExitSTRBroadcastSubscriber();
#ifdef CALL_MANAGER_THERMAL_PROTECTION
        void ThermalLevelChangedBroadcastSubscriber();
#endif

    private:
        std::vector<std::shared_ptr<CallBroadcastSubscriber>> subscriberPtrList_;
    };

private:
    std::unique_ptr<CallStateListener> callStateListenerPtr_;
    std::unique_ptr<CallRequestHandler> CallRequestHandlerPtr_;
    // notify when incoming calls are ignored, not rejected or answered
    std::shared_ptr<IncomingCallWakeup> incomingCallWakeup_;
#ifdef ABILITY_POWER_SUPPORT
    std::shared_ptr<PowerMgr::RunningLock> disconnectedRunningLock_;
#endif
    const int32_t DISCONNECTED_LOCK_TIMEOUT = 2000;

#ifdef SUPPORT_RTT_CALL
    std::shared_ptr<RttCallListener> rttCallListener_ = nullptr;
#endif
    std::shared_ptr<MissedCallNotification> missedCallNotification_;
    std::unique_ptr<CallSettingManager> callSettingManagerPtr_;
    sptr<ISystemAbilityStatusChange> statusChangeListener_ = nullptr;
    DialParaInfo dialSrcInfo_;
    AppExecFwk::PacMap extras_;
    ffrt::mutex mutex_;
    CallStateToApp VoIPCallState_ = CallStateToApp::CALL_STATE_IDLE;
    bool shouldDisconnect = true;
    bool ReduceRingToneVolume_ = false;
    static std::atomic<bool> alarmSeted_;
    std::vector<int32_t> preloadedCallUiRequestPids_ = {};
    struct AnsweredCallQueue {
        bool hasCall = false;
        int32_t callId = 0;
        int32_t videoState = 0;
    } AnsweredCallQueue_;

    struct VoipCallInfo {
        int32_t callId = 10000;
        int32_t state = 0;
        std::string phoneNumber = "";
    } VoipCallInfo_;

    ffrt::task_handle disconnectHandle = nullptr;
    sptr<ApplicationStateObserver> appStateObserver = nullptr;
    sptr<AppExecFwk::IAppMgr> appMgrProxy_ = nullptr;
    
    ffrt::mutex appStateObserverMutex_;
    ffrt::mutex preloadedCallUiRequestPidsMutex_;
    sptr<WearStatusObserver> wearStatusObserver_ = nullptr;
    int32_t wearStatus_ = WEAR_STATUS_INVALID;
    ffrt::mutex wearStatusMutex_;
    ffrt::mutex reminderMutex_;
    ffrt::mutex ringToneMutex_;
    ffrt::task_handle pendingHangupHandle_ = nullptr;
    ffrt::mutex pendingHangupHandleMutex_;
    std::shared_ptr<IncomingFlashReminder> incomingFlashReminder_ {nullptr};
#ifdef CALL_MANAGER_THERMAL_PROTECTION
    std::atomic<int32_t> thermalLevel_ = -1;
#endif
};
} // namespace Telephony
} // namespace OHOS
#endif // CALL_CONTROL_MANAGER_H