using System;
using System.Linq;
using UniRx;
using UnityEngine;

public class CustomerFlow : MonoBehaviour
{
    private IObservable<bool> customerObservable;
    private IObservable<bool> walkerObservable;
    private IObservable<bool> adWalkerObservable;
    private readonly Subject<Unit> adStartObservable = new Subject<Unit>();
    private static readonly float checkHeartInterval = 1f;
    // 歩行者の出現間隔
    private static readonly float walkerInterval = 60f / 6;

    public IObservable<bool> Flow => walkerObservable.Merge(customerObservable, adWalkerObservable);
    
    private void Awake()
    {
        adStartObservable.AddTo(this);
        
        var shopLevelList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopLevelData>(Const.ShopLevelDataSheet);
        // 10分間期待値を来客の間隔に変換
        var intervalList = shopLevelList.Select(shopLevel => (heart: shopLevel.heart, interval: 60f * 10 / shopLevel.customer));
        
        // １秒間隔でハートを確認
        var changeCustomerFlowObservable = Observable.Interval(TimeSpan.FromSeconds(checkHeartInterval))
            .Select(_ => GameDataManager.GameData.Heart)
            .DistinctUntilChanged()
            .Select(heart => intervalList.Last(x => x.heart <= heart).interval);
        
        // お客さん出現タイマー
        customerObservable = changeCustomerFlowObservable
            .DistinctUntilChanged()
            .Do(x => Debug.Log($"changeInterval:{x}"))
            .Select(customerInterval => Observable.Interval(TimeSpan.FromSeconds(customerInterval))
                .Do(_ => Debug.Log($"customer:{GetHashCode()}"))
                .Select(_ => true))
            .Switch();

        // 歩行者出現頻度、立ち止まり確率も設定(歩行者タイマー1分間に6人
        walkerObservable = Observable.Interval(TimeSpan.FromSeconds(walkerInterval))
            .Do(l => Debug.Log($"walker:{GetHashCode()}"))
            .Select(x => false);

        // 宣伝時、タップすると60秒だけ稼働するストリーム
        adWalkerObservable = adStartObservable
            .Delay(TimeSpan.FromSeconds(2f))    
            .Select(x => Observable.Interval(TimeSpan.FromSeconds(3f))
                .Take(TimeSpan.FromSeconds(60f))
                .Do(_ => Debug.Log($"adWalker:{GetHashCode()}"))
                .Select(_ => false))
            .Switch();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
        if (UsayaStorageManager.LoadOrDefault(UsayaStorageFilename.Settings_Data, "DebugManyWalker", false))
        {
            Observable.Timer(TimeSpan.FromSeconds(1f), TimeSpan.FromSeconds(70f)).Subscribe(_ => { adStartObservable.OnNext(default); }).AddTo(this);
        }
#endif
    }

    public void StartAdWalker()
    {
        adStartObservable.OnNext(Unit.Default);
    }
}
