using System;
using Dirichlet.Mediation;
using Runtime.ADAggregator;
using UnityEngine;

public sealed class TapadnAdController : IAdController
{
    public static TapadnControllerOptions CurrentOptions { get; private set; }
    public static string LastSdkVersion { get; private set; }
    public static string LastInitError { get; private set; }

    private Action<bool> _maskAction;
    private Action<string, string> _logEventAction;
    private ADConfig _adConfig;
    private TapadnControllerOptions _options;

    public void Init(ADConfig adConfig, object[] args)
    {
        _adConfig = adConfig;
        _options = TapadnControllerOptions.Resolve(adConfig, args);
        CurrentOptions = _options;

        var sdkConfig = _options.BuildSdkConfig();
        DirichletSdk.Init(
            sdkConfig,
            result =>
            {
                LastInitError = null;
                LastSdkVersion = DirichletSdk.GetVersion();
                EventLog("tapadn_init", "success", result?.Message);
                Debug.Log($"[TapADN] Init success. version={LastSdkVersion}, message={result?.Message}");
                if (_options.RequestPermissionOnInit)
                {
                    DirichletSdk.RequestPermissionIfNecessary();
                }
            },
            error =>
            {
                LastInitError = $"{error?.Code}:{error?.Message}";
                EventLog("tapadn_init_error", error?.Code ?? "unknown", error?.Message);
                Debug.LogError($"[TapADN] Init failed. code={error?.Code}, message={error?.Message}");
            });
    }

    public void SetListener(Action<bool> adMaskAction, Action<string, string> logEventAction)
    {
        _maskAction = adMaskAction;
        _logEventAction = logEventAction;
    }

    public ADPlayer CreateAdPlayer(AD_Type type)
    {
        switch (type)
        {
            case AD_Type.AwardVideo:
                return new TapadnAwardVideoPlayer().Init(_adConfig?.BaseAwardAdKeyValue?.value);
            case AD_Type.Interaction:
                return new TapadnInteractionPlayer().Init(_adConfig?.BaseInteractionAdKeyValue?.value);
            case AD_Type.Splash:
                return new TapadnSplashPlayer().Init(_adConfig?.BaseSplashAdKeyValue?.value);
            default:
                return null;
        }
    }

    public void EventLog(string eventTable, string eventValue, string eventMessage = null)
    {
        _logEventAction?.Invoke(eventTable, eventValue);
    }

    public void SetMask(bool isOpen)
    {
        _maskAction?.Invoke(isOpen);
    }
}
