daily pastebin goal
74%
SHARE
TWEET

Untitled

a guest Dec 16th, 2018 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine.UI;
  5. using System;
  6. using System.Collections;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using Com.TheFallenGames.OSA.Core;
  11. using Com.TheFallenGames.OSA.CustomParams;
  12. using frame8.Logic.Misc.Other.Extensions;
  13. using JamTracks;
  14. using MaterialUI;
  15. using MEC;
  16. using Sirenix.Utilities;
  17. using UnityEngine.Events;
  18.  
  19. public class JamPacksScrollRectItemsAdapter : OSA<JamPacksParams, JamPacksViewsHolder>
  20. {
  21.     public UnityEvent OnItemsUpdated;
  22.  
  23.     private Dictionary<JamPacksViewsHolder, PackButtonModel> vHolders = new Dictionary<JamPacksViewsHolder, PackButtonModel>();
  24.     private Dictionary<PackButtonModel, bool> modelChangeVisualAfterStartWaiting = new Dictionary<PackButtonModel, bool>();
  25.  
  26.     [SerializeField] private int updateListRate = 3;
  27.     private int frameCount = 0;
  28.     private int _IndexOfCurrentlyExpandedItem;
  29.     private List<Pack> packsStates = new List<Pack>();
  30.  
  31.  
  32.     protected override void Start()
  33.     {
  34.         base.Start();
  35.         Init();
  36.  
  37.         StartMethods();
  38.     }
  39.  
  40.     private void StartMethods()
  41.     {
  42.         try
  43.         {
  44.             LoadPacksState();
  45.         }
  46.         catch (Exception e)
  47.         {
  48.             if (Debug.isDebugBuild)
  49.                 Debug.Log("!!!!!!! ERROR while LoadPacksState " + e.Message);
  50.         }
  51.  
  52.         _Params.Adapter = this;
  53.         _Params.OnPacksUpdated.AddListener(OnReceivedNewModels);
  54.         _Params.OnSortModels.AddListener(OnSortModels);
  55.         _Params.InitPacks();
  56.         //OnReceivedNewModels(_Params.FilteredPacks.Count);
  57.         RegisterEventsListeners();
  58.         EventManager.TriggerEvent("PacksAdapterIsReady");
  59.  
  60.         Timing.RunCoroutine(CheckInternetConnection(), Segment.SlowUpdate);
  61.     }
  62.  
  63.     private void OnApplicationQuit()
  64.     {
  65.         SavePacksState();
  66.     }
  67.  
  68.     public void SavePacksState()
  69.     {
  70.         packsStates = new List<Pack>(_Params.packsLibrary.packs);
  71.         ES3.Save<List<Pack>>("packsStates", packsStates, CommonSettings.Instance.Es3Settings);
  72.     }
  73.  
  74.     private void LoadPacksState()
  75.     {
  76.         if (ES3.KeyExists("packsStates", CommonSettings.Instance.Es3Settings))
  77.         {
  78.             packsStates = ES3.Load<List<Pack>>("packsStates", CommonSettings.Instance.Es3Settings);
  79.             foreach (var pack in _Params.packsLibrary.packs)
  80.             {
  81.                 Pack packState = packsStates.FirstOrDefault(el => el.id == pack.id);
  82.                 if (packState != null)
  83.                 {
  84.                     pack.aviable = packState.aviable;
  85.                     pack.hasPreview = packState.hasPreview;
  86.                     pack.included = packState.included;
  87.                     pack.showInList = packState.showInList;
  88.                 }
  89.             }
  90.         }
  91.         else
  92.         {
  93.             SavePacksState();
  94.         }
  95.     }
  96.  
  97.     public Dictionary<JamPacksViewsHolder, PackButtonModel> GetVHHolders()
  98.     {
  99.         return vHolders;
  100.     }
  101.  
  102.     private void RegisterEventsListeners()
  103.     {
  104.         EventManager.StartListening("Packs_ResetAllPacksPlayButtons", _Params.ResetAllPacksPlayButtons);
  105.         EventManager.StartListening("Packs_IncludeAllPacks", _Params.IncludeAllPacks);
  106.         EventManager.StartListening("Packs_ExcludeAllPacks", _Params.ExcludeAllPacks);
  107.         EventManager.StartListening("Playlist_FilterAfterPacksChanges", SavePacksState);
  108.         EventManager.StartListeningCustom("PackPurchased", _Params.OnPackPurchased);
  109.         EventManager.StartListeningCustom("ApplyPacksStyleFilterOptions", _Params.FilterPacksByStyle);
  110.         //EventManager.StartListening("PurchaserInitialized", _Params.ChangePacksPrices);      
  111.     }
  112.  
  113.     /*private bool GetTrackCachedState(string trackName)
  114.     {
  115.         return File.Exists(@GetTrackPathInFilesystem(trackName));
  116.     }
  117.  
  118.     private string GetTrackPathInFilesystem(string trackName)
  119.     {
  120.         return FileManager.Instance.GetAndroidFriendlyFilesPath() + "/" + trackName.ToLower() + ".mp3";
  121.     }*/
  122.  
  123.     /*private bool GetTrackCachedState(TrackButtonModel track)
  124.     {
  125.         return File.Exists(@GetTrackPathInFilesystem(track)) && new System.IO.FileInfo(@GetTrackPathInFilesystem(track)).Length == track.fileSize;
  126.     }
  127.  
  128.     private string GetTrackPathInFilesystem(TrackButtonModel track)
  129.     {
  130.         return FileManager.Instance.GetAndroidFriendlyFilesPath() + "/" + track.clipName.ToLower() + ".mp3";
  131.     }*/
  132.  
  133.     private IEnumerator<float> CheckInternetConnection()
  134.     {
  135.         while (true)
  136.         {
  137.             if (Application.internetReachability != NetworkReachability.NotReachable)
  138.             {
  139.                 _Params.ChangePacksPrices();
  140.             }
  141.  
  142.             yield return 0f;
  143.         }
  144.     }
  145.  
  146.     protected override void Update()
  147.     {
  148.         base.Update();
  149.  
  150.         if (frameCount > (int) (1 / Time.deltaTime / updateListRate))
  151.         {
  152.             foreach (var vh in vHolders)
  153.             {
  154.                 if (!modelChangeVisualAfterStartWaiting.ContainsKey(vh.Value))
  155.                 {
  156.                     modelChangeVisualAfterStartWaiting.Add(vh.Value, false);
  157.                 }
  158.  
  159.                 if (vh.Value.previewTrack.waitingLoading)
  160.                 {
  161.                     if (!modelChangeVisualAfterStartWaiting[vh.Value])
  162.                     {
  163.                         modelChangeVisualAfterStartWaiting[vh.Value] = true;
  164.                         vh.Key.ChangeElementLoadingState(vh.Value);
  165.                     }
  166.  
  167.                     continue;
  168.                 }
  169.  
  170.                 if (vh.Value.previewTrack.loading)
  171.                 {
  172.                     vh.Key.progressBar.SetProgress(vh.Value.previewTrack.loadingValue, false);
  173.                     modelChangeVisualAfterStartWaiting[vh.Value] = false;
  174.                     vh.Key.ChangeElementLoadingState(vh.Value);
  175.                     continue;
  176.                 }
  177.  
  178.                 if (!vh.Value.previewTrack.loading && vh.Value.previewTrack.loaded || (!vh.Value.previewTrack.loading && !vh.Value.previewTrack.loaded && !vh.Value.previewTrack.waitingLoading))
  179.                 {
  180.                     vh.Key.ChangeElementLoadingState(vh.Value);
  181.                     vh.Key.SetPlayButtonIcon(vh.Value);
  182.                 }
  183.  
  184.                 if (_Params.PricesIninitilized)
  185.                 {
  186.                     vh.Key.ChangePacksPriceString(vh.Value);
  187.                     vh.Key.ChangePacksPackMenuState(vh.Value);
  188.                 }
  189.             }
  190.  
  191.             frameCount = 0;
  192.         }
  193.  
  194.         frameCount++;
  195.  
  196.         foreach (var vh in vHolders)
  197.         {
  198.             vh.Key.progressBar.transform.position = vh.Key.progressBarTMP.transform.position;
  199.             vh.Key.ChangePacksDescButtonRotation(vh.Value);
  200.             vh.Key.ChangeIncludeSwitchVisibility(vh.Value);
  201.         }
  202.     }
  203.  
  204.     protected override void OnItemHeightChangedPreTwinPass(JamPacksViewsHolder vh)
  205.     {
  206.         base.OnItemHeightChangedPreTwinPass(vh);
  207.  
  208.         if (_Params.GroupPacks)
  209.         {
  210.             //_Params.flattenedVisibleHierarchy[vh.ItemIndex].HasPendingSizeChange = false;
  211.             /*if (_Params.flattenedVisibleHierarchy[vh.ItemIndex].IsDirectory)
  212.                 _Params.flattenedVisibleHierarchy[vh.ItemIndex].HasPendingSizeChange = false;*/
  213.         }
  214.         else
  215.         {
  216.             _Params.Data[vh.ItemIndex].HasPendingSizeChange = false;
  217.         }
  218.  
  219.         vh.contentSizeFitter.enabled = false;
  220.     }
  221.  
  222.  
  223.     /// <inheritdoc/>
  224.     public override void ChangeItemsCount(ItemCountChangeMode changeMode, int itemsCount, int indexIfInsertingOrRemoving = -1, bool contentPanelEndEdgeStationary = false, bool keepVelocity = false)
  225.     {
  226.         _IndexOfCurrentlyExpandedItem = -1; // at initialization, and each time the item count changes, this should be invalidated
  227.  
  228.         base.ChangeItemsCount(changeMode, itemsCount, indexIfInsertingOrRemoving, contentPanelEndEdgeStationary, keepVelocity);
  229.     }
  230.  
  231.     PackButtonModel CreateNewModelNode(int itemIndex, int numChildren)
  232.     {
  233.         var m = CreateNewModel(itemIndex, true);
  234.         m.children = new PackButtonModel[numChildren];
  235.  
  236.         return m;
  237.     }
  238.  
  239.     PackButtonModel CreateNewModel(int itemId, bool isDirectory)
  240.     {
  241.         TrackButtonModel previewTrack = new TrackButtonModel();
  242.         var filteredPack = _Params.FilteredPacks.Find(el => el.id == itemId);
  243.  
  244.         if (filteredPack != null)
  245.         {
  246.             previewTrack.clipName = "[" + filteredPack.name.Replace("v.", "v").Replace("'n'", "n").ToLower() + "] preview";
  247.             bool trackCached = FileManager.Instance.GetTrackCachedState(previewTrack);
  248.             previewTrack.loaded = trackCached;
  249.             previewTrack.loading = false;
  250.             previewTrack.waitingLoading = false;
  251.             previewTrack.id = Int32.MaxValue - filteredPack.id;
  252.         }
  253.  
  254.         Debug.Log($"CreateNewModel itemId = {itemId}");
  255.  
  256.         return new PackButtonModel()
  257.                {
  258.                    id = isDirectory ? -1 : itemId,
  259.                    aviable = isDirectory || filteredPack.aviable,
  260.                    included = isDirectory || filteredPack.included,
  261.                    showInList = isDirectory || filteredPack.showInList,
  262.                    hasPreview = !isDirectory && filteredPack.hasPreview,
  263.                    title = isDirectory
  264.                                ? _Params.PacksGrouped.Keys.ElementAtOrDefault(itemId) != null ? _Params.PacksGrouped.Keys.ElementAtOrDefault(itemId) : ""
  265.                                : filteredPack.Title,
  266.                    name = isDirectory ? "" : filteredPack.name,
  267.                    bg = isDirectory ? null : filteredPack.bg,
  268.                    bg_mini = isDirectory ? null : filteredPack.bg_mini,
  269.                    price = isDirectory ? 0 : filteredPack.Price,
  270.                    priceLocalizedString = isDirectory ? "" : filteredPack.PriceLocalized,
  271.                    Description = isDirectory ? "" : filteredPack.Description,
  272.                    descExpanded = false,
  273.                    previewTrack = isDirectory ? null : previewTrack
  274.                };
  275.     }
  276.  
  277.     PackButtonModel CreateNewModelNotGrouped(int itemIndex)
  278.     {
  279.         TrackButtonModel previewTrack = new TrackButtonModel();
  280.         previewTrack.clipName = "[" + _Params.FilteredPacks[itemIndex].name.Replace("v.", "v").Replace("'n'", "n").ToLower() + "] preview";
  281.         bool trackCached = FileManager.Instance.GetTrackCachedState(previewTrack);
  282.         previewTrack.loaded = trackCached;
  283.         previewTrack.loading = false;
  284.         previewTrack.waitingLoading = false;
  285.         previewTrack.id = Int32.MaxValue - _Params.FilteredPacks[itemIndex].id;
  286.  
  287.         return new PackButtonModel()
  288.                {
  289.                    id = _Params.FilteredPacks[itemIndex].id,
  290.                    aviable = _Params.FilteredPacks[itemIndex].aviable,
  291.                    included = _Params.FilteredPacks[itemIndex].included,
  292.                    showInList = _Params.FilteredPacks[itemIndex].showInList,
  293.                    hasPreview = _Params.FilteredPacks[itemIndex].hasPreview,
  294.                    title = _Params.FilteredPacks[itemIndex].Title,
  295.                    name = _Params.FilteredPacks[itemIndex].name,
  296.                    bg = _Params.FilteredPacks[itemIndex].bg,
  297.                    bg_mini = _Params.FilteredPacks[itemIndex].bg_mini,
  298.                    price = _Params.FilteredPacks[itemIndex].Price,
  299.                    priceLocalizedString = _Params.FilteredPacks[itemIndex].PriceLocalized,
  300.                    Description = _Params.FilteredPacks[itemIndex].Description,
  301.                    descExpanded = false,
  302.                    previewTrack = previewTrack
  303.                };
  304.     }
  305.  
  306.     public void OnSortModels()
  307.     {
  308.         if (_Params.GroupPacks)
  309.         {
  310.             ResetItems(_Params.flattenedVisibleHierarchy.Count);
  311.         }
  312.         else
  313.         {
  314.             ResetItems(_Params.Data.Count);
  315.         }
  316.  
  317.         if (gameObject.activeInHierarchy)
  318.         {
  319.             if (!_Params.GroupPacks)
  320.             {
  321.                 SmoothScrollTo(0, CommonSettings.Instance.playListScrollToSpeed);
  322.             }
  323.         }
  324.  
  325.         OnItemsUpdated?.Invoke();
  326.     }
  327.  
  328.     public async void OnReceivedNewModels(int newCount)
  329.     {
  330.         await OnReceivedNewModelsCoroutine(newCount);
  331.     }
  332.  
  333.     private IEnumerator OnReceivedNewModelsCoroutine(int newCount)
  334.     {
  335.         if (Debug.isDebugBuild)
  336.             Debug.Log("Packs OnReceivedNewModelsCoroutine newCount = " + newCount);
  337.  
  338.         yield return null;
  339.  
  340.         vHolders.Clear();
  341.         var newModels = new PackButtonModel[newCount];
  342.  
  343.         if (_Params.GroupPacks)
  344.         {
  345.             //_Params.PacksGrouped.Count + 1, потому что добавляем без стиля фришную библу
  346.             //_Params.hierarchyRootNode = CreateNewModelNode(0, _Params.PacksGrouped.Count);
  347.             _Params.hierarchyRootNode = CreateNewModelNode(0, _Params.PacksGrouped.Count);
  348.             int packModelIndex = 0;
  349.             //for (int i = 0; i < _Params.hierarchyRootNode.children.Length - 1; i++)
  350.             for (int i = 0; i < _Params.hierarchyRootNode.children.Length; i++)
  351.             {
  352.                 _Params.hierarchyRootNode.children[i] = CreateNewModelNode(i, _Params.PacksGrouped.ElementAt(i).Value.Count);
  353.  
  354.                 int j = 0;
  355.                 foreach (var pack in _Params.PacksGrouped.ElementAt(i).Value)
  356.                 {
  357.                     _Params.hierarchyRootNode.children[i].children[j] = CreateNewModel(pack.id, false);
  358.                     j++;
  359.                     packModelIndex++;
  360.                 }
  361.             }
  362.  
  363.             //тут добавляем фришную либу c id 1, она идет НЕ как папка
  364. //            /_Params.hierarchyRootNode.children[_Params.hierarchyRootNode.children.Length - 1] = CreateNewModel(1, false);
  365.  
  366.  
  367.             _Params.flattenedVisibleHierarchy = new List<PackButtonModel>(_Params.hierarchyRootNode.children);
  368.  
  369.             newModels = _Params.flattenedVisibleHierarchy.ToArray();
  370.         }
  371.         else
  372.         {
  373.             for (int i = 0; i < newCount; ++i)
  374.             {
  375.                 newModels[i] = CreateNewModelNotGrouped(i);
  376.             }
  377.         }
  378.  
  379.         //yield return null;
  380.  
  381.         if (!_Params.GroupPacks)
  382.         {
  383.             _Params.Data.Clear();
  384.             _Params.Data.AddRange(newModels);
  385.         }
  386.  
  387.         //yield return null;
  388.  
  389.         if (_Params.GroupPacks)
  390.         {
  391.             ResetItems(_Params.flattenedVisibleHierarchy.Count);
  392.         }
  393.         else
  394.         {
  395.             ResetItems(_Params.Data.Count);
  396.         }
  397.  
  398.         //yield return null;
  399.  
  400.         if (gameObject.activeInHierarchy)
  401.         {
  402.             SmoothScrollTo(0, CommonSettings.Instance.playListScrollToSpeed);
  403.         }
  404.  
  405.         OnItemsUpdated?.Invoke();
  406.     }
  407.  
  408.     protected override JamPacksViewsHolder CreateViewsHolder(int itemIndex)
  409.     {
  410.         var instance = new JamPacksViewsHolder();
  411.         instance.Init(_Params.itemPrefab, itemIndex);
  412.         instance.button.onClick.AddListener(() => OnDirectoryFoldOutClicked(instance));
  413.  
  414.         if (_Params.GroupPacks)
  415.         {
  416.             if (!_Params.flattenedVisibleHierarchy[instance.ItemIndex].IsDirectory && !vHolders.ContainsKey(instance))
  417.             {
  418.                 vHolders.Add(instance, null);
  419.             }
  420.         }
  421.         else if (!vHolders.ContainsKey(instance))
  422.         {
  423.             vHolders.Add(instance, null);
  424.         }
  425.  
  426.         instance.expandDescButton.onClick.AddListener(() => OnExpandButtonClick(instance));
  427.         return instance;
  428.     }
  429.  
  430.     private void OnDirectoryFoldOutClicked(JamPacksViewsHolder vh)
  431.     {
  432.         if (!_Params.GroupPacks)
  433.             return;
  434.  
  435.         var model = _Params.flattenedVisibleHierarchy[vh.ItemIndex];
  436.  
  437.         if (model.IsDirectory)
  438.         {
  439.             if (Debug.isDebugBuild)
  440.                 Debug.Log($"OnDirectoryFoldOutClicked model.children.Length = {model.children.Length}");
  441.  
  442.             bool wasExpanded = model.expanded;
  443.             model.expanded = !model.expanded;
  444.             int nextIndex = vh.ItemIndex + 1;
  445.  
  446.             if (wasExpanded)
  447.             {
  448.                 int i = vh.ItemIndex + 1 + model.children.Length;
  449.                 int countToRemove = i - nextIndex;
  450.  
  451.                 if (countToRemove > 0)
  452.                 {
  453.                     _Params.flattenedVisibleHierarchy.RemoveRange(nextIndex, countToRemove);
  454.                     RemoveItems(nextIndex, countToRemove);
  455.                     vHolders.Clear();
  456.                 }
  457.             }
  458.             else
  459.             {
  460.                 if (model.children.Length > 0)
  461.                 {
  462.                     _Params.flattenedVisibleHierarchy.InsertRange(nextIndex, model.children);
  463.                     InsertItems(nextIndex, model.children.Length);
  464.                     vHolders.Clear();
  465.                 }
  466.             }
  467.  
  468.             //model.HasPendingSizeChange = true;
  469.             vh.UpdateViews(model, _Params);
  470.             _Params.OnSortModels.Invoke();
  471.  
  472.             //model.HasPendingSizeChange = true;
  473.         }
  474.     }
  475.  
  476.     private void OnExpandButtonClick(JamPacksViewsHolder vh)
  477.     {
  478.         PackButtonModel model = null;
  479.         if (_Params.GroupPacks)
  480.         {
  481.             model = _Params.flattenedVisibleHierarchy[vh.ItemIndex];
  482.         }
  483.         else
  484.         {
  485.             model = _Params.Data[vh.ItemIndex];
  486.         }
  487.  
  488.         model.descExpanded = !model.descExpanded;
  489.         // No need to set HasPendingSizeChange=true, since the rectTransform will be updated immediately
  490.         vh.UpdateExpandedState(model.descExpanded);
  491.  
  492.         // If you're enabling/disabling children that can have an impact on the item's size (as opposed to just changing their content - like the Text.text property),
  493.         // this is he only reliable way of dynamically changing an item's size through SRIA v3.2 or lower.
  494.  
  495.  
  496.         // The size changed. Enable the CSF component
  497.         // This is not needed here in the current case (replace it with vh.contentSizeFitter.enabled=true if you want),
  498.         // since we're using the "ForceXXX" version of the layout rebuilding function,
  499.         // but we should do it in general, in case your viewholder has some own logic to be executed right before a rebuild event.
  500.         vh.MarkForRebuild();
  501.  
  502.         // The CSF component will resize the root accordingly
  503.         // Use Canvas.ForceUpdateCanvases() instead, if on old unity version
  504.         LayoutRebuilder.ForceRebuildLayoutImmediate(vh.root);
  505.  
  506.         // The CSF component was used to estimate the item's size, but the adapter itself
  507.         // should set it (along with correctly setting the item's position, shifting other items, updating sizes cache etc.)
  508.         RequestChangeItemSizeAndUpdateLayout(vh, vh.root.rect.height);
  509.  
  510.         // MarkForRebuild has set it to true; We used it, now set it back to false - not too important,
  511.         // because it'll be disabled anyway next time it's recycled, but it's nice to clean after ourselves:)
  512.         vh.contentSizeFitter.enabled = false;
  513.  
  514.         if (model.descExpanded)
  515.         {
  516.             //SmoothScrollTo(vh.ItemIndex, 0.2f);
  517.         }
  518.     }
  519.  
  520.     protected override void UpdateViewsHolder(JamPacksViewsHolder newOrRecycled)
  521.     {
  522.         PackButtonModel model = null;
  523.  
  524.         if (_Params.GroupPacks)
  525.         {
  526.             if (!_Params.flattenedVisibleHierarchy[newOrRecycled.ItemIndex].IsDirectory)
  527.             {
  528.                 if (vHolders.ContainsKey(newOrRecycled))
  529.                 {
  530.                     vHolders[newOrRecycled] = _Params.flattenedVisibleHierarchy[newOrRecycled.ItemIndex];
  531.                 }
  532.                 else
  533.                 {
  534.                     vHolders.Add(newOrRecycled, _Params.flattenedVisibleHierarchy[newOrRecycled.ItemIndex]);
  535.                 }
  536.             }
  537.  
  538.             model = _Params.flattenedVisibleHierarchy[newOrRecycled.ItemIndex];
  539.         }
  540.         else
  541.         {
  542.             if (vHolders.ContainsKey(newOrRecycled))
  543.             {
  544.                 vHolders[newOrRecycled] = _Params.Data[newOrRecycled.ItemIndex];
  545.             }
  546.             else
  547.             {
  548.                 vHolders.Add(newOrRecycled, _Params.Data[newOrRecycled.ItemIndex]);
  549.             }
  550.  
  551.             model = _Params.Data[newOrRecycled.ItemIndex];
  552.         }
  553.  
  554.         newOrRecycled.UpdateViews(model, _Params);
  555.  
  556.         if (newOrRecycled.contentSizeFitter.enabled)
  557.         {
  558.             newOrRecycled.contentSizeFitter.enabled = false;
  559.         }
  560.  
  561.         if (model != null && model.HasPendingSizeChange)
  562.         {            
  563.             // Height will be available before the next 'twin' pass, inside OnItemHeightChangedPreTwinPass() callback (see above)
  564.             newOrRecycled.MarkForRebuild(); // will enable the content size fitter
  565.             ScheduleComputeVisibilityTwinPass();
  566.         }
  567.     }
  568.  
  569.     protected override void RebuildLayoutDueToScrollViewSizeChange()
  570.     {
  571.         // Invalidate the last sizes so that they'll be re-calculated
  572.         if (_Params.GroupPacks)
  573.         {
  574.             foreach (var model in _Params.flattenedVisibleHierarchy)
  575.             {
  576.                 //if (!model.IsDirectory)
  577.                     //model.HasPendingSizeChange = true;
  578.             }
  579.         }
  580.         else
  581.         {
  582.             foreach (var model in _Params.Data)
  583.             {
  584.                 model.HasPendingSizeChange = true;
  585.             }
  586.         }
  587.  
  588.         base.RebuildLayoutDueToScrollViewSizeChange();
  589.     }
  590. }
  591.  
  592. public class JamPacksViewsHolder : BaseItemViewsHolder
  593. {
  594.     public CircularProgressIndicator progressBar;
  595.     public CircularProgressIndicator progressBarTMP;
  596.  
  597.     public Button expandDescButton;
  598.     public Button buyButton;
  599.     public MaterialSwitch includeSwitch;
  600.     public Transform packDesc;
  601.     public Text packDescText;
  602.     public Transform packDescGO;
  603.     public Button playPreviewButton;
  604.     public VectorImage playPreviewIcon;
  605.     public CanvasGroup playPreviewButtonCanvasGroup;
  606.     public Text packTitle;
  607.     public Image packImage;
  608.     public Text tracksCount;
  609.     public Text timeCount;
  610.     public Text price;
  611.     public Transform packPreviewButtonGO;
  612.     public Transform packPreviewTextGO;
  613.     public RectTransform packDescTextRect;
  614.     public LayoutElement packDescTextLayoutElement;
  615.     public MaterialDropdown packMenu;
  616.     public Button button;
  617.     public Transform dirStateGO;
  618.     public Transform packStateGO;
  619.     public Text dirLabel;
  620.     public VectorImage dirIcon;
  621.     public Text dirCount;
  622.  
  623.     private Match packMatch = null;
  624.     public PackButtonModel _Model;
  625.     public JamPacksParams _Params;
  626.  
  627.     public bool changeIncludeSwitchFromVH = true;
  628.  
  629.     public ContentSizeFitter contentSizeFitter { get; private set; }
  630.  
  631.     private int maxTracksSimLoading = 5;
  632.     private int currentLoadingCount = 0;
  633.  
  634.     private ImageData playIcon;
  635.     private ImageData pauseIcon;
  636.  
  637.     private ImageData dirExpandMoreIcon = null;
  638.     private ImageData dirExpandLessIcon = null;
  639.  
  640.     public override void CollectViews()
  641.     {
  642.         base.CollectViews();
  643.         contentSizeFitter = root.GetComponent<ContentSizeFitter>();
  644.  
  645.         /*root.GetComponentAtPath("Desc/PackDesc/Text", out packDescText);
  646.         root.GetComponentAtPath("Desc", out packDescGO);
  647.  
  648.         root.GetComponentAtPath("Top/Buttons/ExpandButton", out expandDescButton);
  649.         root.GetComponentAtPath("Top/Buttons/BuyButton", out buyButton);
  650.         root.GetComponentAtPath("Top/Buttons/Switch", out includeSwitch);
  651.         root.GetComponentAtPath("Top/TrackPackImg", out packImage);
  652.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button/DownloadProgress_Circle", out progressBar);
  653.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button", out packPreviewButtonGO);
  654.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Text", out packPreviewTextGO);
  655.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button/DownloadProgress_CircleTMP", out progressBarTMP);
  656.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button/PlayIcon", out playPreviewButton);
  657.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button/PlayIcon", out playPreviewButtonCanvasGroup);
  658.         root.GetComponentAtPath("Top/Title/Desc/PackPreview/Button/PlayIcon/Icon", out playPreviewIcon);
  659.         root.GetComponentAtPath("Top/Title/Top/Dropdown", out packMenu);
  660.  
  661.         root.GetComponentAtPath("Top/Title/Top/PackLabel", out packTitle);
  662.         root.GetComponentAtPath("Top/Title/Desc/TracksCount", out tracksCount);
  663.         root.GetComponentAtPath("Top/Title/Desc/TimeCount", out timeCount);
  664.         root.GetComponentAtPath("Top/Title/Desc/Price", out price);
  665.         root.GetComponentAtPath("Desc/PackDesc", out packDesc);
  666.         root.GetComponentAtPath("Desc/PackDesc/Text", out packDescTextLayoutElement);
  667.         root.GetComponentAtPath("Desc/PackDesc/Text", out packDescTextRect);*/
  668.  
  669.  
  670.         root.GetComponentAtPath("PackState/Desc/PackDesc/Text", out packDescText);
  671.         root.GetComponentAtPath("PackState/Desc", out packDescGO);
  672.         root.GetComponentAtPath("PackState/Top/Buttons/ExpandButton", out expandDescButton);
  673.         root.GetComponentAtPath("PackState/Top/Buttons/BuyButton", out buyButton);
  674.         root.GetComponentAtPath("PackState/Top/Buttons/Switch", out includeSwitch);
  675.         root.GetComponentAtPath("PackState/Top/TrackPackImg", out packImage);
  676.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button/DownloadProgress_Circle", out progressBar);
  677.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button", out packPreviewButtonGO);
  678.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Text", out packPreviewTextGO);
  679.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button/DownloadProgress_CircleTMP", out progressBarTMP);
  680.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button/PlayIcon", out playPreviewButton);
  681.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button/PlayIcon", out playPreviewButtonCanvasGroup);
  682.         root.GetComponentAtPath("PackState/Top/Title/Desc/PackPreview/Button/PlayIcon/Icon", out playPreviewIcon);
  683.         root.GetComponentAtPath("PackState/Top/Title/Top/Dropdown", out packMenu);
  684.         root.GetComponentAtPath("PackState/Top/Title/Top/PackLabel", out packTitle);
  685.         root.GetComponentAtPath("PackState/Top/Title/Desc/TracksCount", out tracksCount);
  686.         root.GetComponentAtPath("PackState/Top/Title/Desc/TimeCount", out timeCount);
  687.         root.GetComponentAtPath("PackState/Top/Title/Desc/Price", out price);
  688.         root.GetComponentAtPath("PackState/Desc/PackDesc", out packDesc);
  689.         root.GetComponentAtPath("PackState/Desc/PackDesc/Text", out packDescTextLayoutElement);
  690.         root.GetComponentAtPath("PackState/Desc/PackDesc/Text", out packDescTextRect);
  691.         root.GetComponentAtPath("DirState", out dirStateGO);
  692.         root.GetComponentAtPath("DirState/DirLabel", out dirLabel);
  693.         root.GetComponentAtPath("DirState/Icon", out dirIcon);
  694.         root.GetComponentAtPath("DirState/Count", out dirCount);
  695.         root.GetComponentAtPath("PackState", out packStateGO);
  696.  
  697.  
  698.         /*root.GetComponentAtPath("Top/Buttons/ExpandButton", out expandDescButton);
  699.         root.GetComponentAtPath("Top/Buttons/BuyButton", out buyButton);
  700.         root.GetComponentAtPath("Top/Buttons/Switch", out includeSwitch);
  701.         root.GetComponentAtPath("Top/TrackPackImg", out packImage);
  702.         root.GetComponentAtPath("Top/PackPreview/Button/DownloadProgress_Circle", out progressBar);
  703.         root.GetComponentAtPath("Top/PackPreview/Button", out packPreviewButtonGO);
  704.         root.GetComponentAtPath("Top/PackPreview/Text", out packPreviewTextGO);
  705.         root.GetComponentAtPath("Top/PackPreview/Button/DownloadProgress_CircleTMP", out progressBarTMP);
  706.         root.GetComponentAtPath("Top/PackPreview/Button/PlayIcon", out playPreviewButton);
  707.         root.GetComponentAtPath("Top/PackPreview/Button/PlayIcon", out playPreviewButtonCanvasGroup);
  708.         root.GetComponentAtPath("Top/PackPreview/Button/PlayIcon/Icon", out playPreviewIcon);
  709.         root.GetComponentAtPath("Top/PackPreview/Dropdown", out packMenu);
  710.  
  711.         root.GetComponentAtPath("Top/Title/PackLabel", out packTitle);
  712.         root.GetComponentAtPath("Top/Title/Desc/TracksCount", out tracksCount);
  713.         root.GetComponentAtPath("Top/Title/Desc/TimeCount", out timeCount);
  714.         root.GetComponentAtPath("Top/Title/Desc/Price", out price);
  715.         root.GetComponentAtPath("Desc/PackDesc", out packDesc);
  716.         root.GetComponentAtPath("Desc/PackDesc/Text", out packDescTextLayoutElement);
  717.         root.GetComponentAtPath("Desc/PackDesc/Text", out packDescTextRect);*/
  718.  
  719.         playPreviewButton.onClick.AddListener(OnPlayPreviewButtonClick);
  720.         buyButton.onClick.AddListener(OnBuyButtonClick);
  721.         includeSwitch.toggle.onValueChanged.AddListener(OnIncludeSwitchValueChanged);
  722.         price.text = I2.Loc.LocalizationManager.GetTranslation("Common/price_not_aviable");
  723.         button = root.GetComponent<Button>();
  724.  
  725.         packMenu.gameObject.SetActive(true);
  726.         for (int i = 0; i < packMenu.optionDataList.options.Count; i++)
  727.         {
  728.             var _i = i;
  729.             packMenu.optionDataList.options[i].onOptionSelected += () => {
  730.                 if (_Model == null)
  731.                     return;
  732.  
  733.                 EventManager.TriggerEventCustom("PackMenuClicked", new Dictionary<string, string>
  734.                                                                    {
  735.                                                                        {"menuIndex", _i.ToString()},
  736.                                                                        {"packId", _Model.id.ToString()}
  737.                                                                    });
  738.             };
  739.         }
  740.  
  741.         packMenu.gameObject.SetActive(CommonSettings.Instance.Premium);
  742.  
  743.         playIcon = MaterialIconHelper.GetIcon("play_circle_outline");
  744.         pauseIcon = MaterialIconHelper.GetIcon("pause_circle_outline");
  745.  
  746.         if (dirExpandMoreIcon == null)
  747.             dirExpandMoreIcon = MaterialIconHelper.GetIcon("expand_more");
  748.         if (dirExpandLessIcon == null)
  749.             dirExpandLessIcon = MaterialIconHelper.GetIcon("expand_less");
  750.     }
  751.  
  752.     private void OnIncludeSwitchValueChanged(bool isOn)
  753.     {
  754.         if (_Model == null)
  755.             return;
  756.  
  757.         if (_Params.packsLibrary.packs.Any(el => el.id == _Model.id))
  758.         {
  759.             if (_Model.included != isOn)
  760.             {
  761.                 _Params.packsLibrary.packs.Find(el => el.id == _Model.id).included = isOn;
  762.                 _Model.included = isOn;
  763.                 EventManager.TriggerEvent("Playlist_FilterAfterPacksChanges");
  764.                 EventManager.TriggerEventCustom("UpdateFiltersFields", new Dictionary<string, string>
  765.                                                                        {
  766.                                                                            {"packId", _Model.id.ToString()}
  767.                                                                        });
  768.             }
  769.  
  770.             ChangeIncludeSwitchStatus(isOn);
  771.         }
  772.     }
  773.  
  774.     private void OnBuyButtonClick()
  775.     {
  776.         if (!CommonSettings.Instance.ConnectedOrDialog())
  777.             return;
  778.  
  779.         PackProduct packProduct = null;
  780.         packProduct = Purchaser.Instance.NC_Products_Packs.FirstOrDefault(el => el.PackID == _Model.id);
  781.         if (packProduct != null)
  782.         {
  783.             Purchaser.Instance.BuyProductID(packProduct.Name);
  784.         }
  785.         else
  786.         {
  787.             if (Debug.isDebugBuild)
  788.                 Debug.Log("!!! ERROR packProduct == null");
  789.         }
  790.     }
  791.  
  792.     private void OnPlayPreviewButtonClick()
  793.     {
  794.         if (_Model == null)
  795.             return;
  796.  
  797.         if (progressBar.transform.parent != _Params.content)
  798.         {
  799.             progressBar.transform.SetParent(_Params.content, true);
  800.         }
  801.  
  802.         _Params.PlayStreamingPreviewTrack(_Model);
  803.         /*if (_Model.previewTrack.loaded)
  804.         {
  805.             _Params.PlayPreviewTrack(_Model);
  806.         }
  807.         else
  808.         {
  809.             _Params.DownloadPreviewTrack(_Model);
  810.         }*/
  811.     }
  812.  
  813.     public void UpdateExpandedState(bool expanded)
  814.     {
  815.         packDescGO.gameObject.SetActive(expanded);
  816.     }
  817.  
  818.     public override void MarkForRebuild()
  819.     {
  820.         base.MarkForRebuild();
  821.         if (contentSizeFitter)
  822.         {
  823.             contentSizeFitter.enabled = true;
  824.         }
  825.     }
  826.  
  827.     public void ChangePacksDescButtonRotation(PackButtonModel model)
  828.     {
  829.         expandDescButton.transform.localRotation = model.descExpanded
  830.                                                        ? Quaternion.Euler(new Vector3(0, 0, 180))
  831.                                                        : Quaternion.Euler(Vector3.zero);
  832.     }
  833.  
  834.     public void ChangePacksPriceString(PackButtonModel model)
  835.     {
  836.         price.text = model.priceLocalizedString;
  837.         price.gameObject.SetActive(!model.aviable);
  838.     }
  839.  
  840.     public void ChangePacksPackMenuState(PackButtonModel model)
  841.     {
  842.         packMenu.gameObject.SetActive(CommonSettings.Instance._premium && model.aviable);
  843.     }
  844.  
  845.     public void ChangeElementLoadingState(PackButtonModel model)
  846.     {
  847.         progressBar.gameObject.SetActive(model.previewTrack.loading || model.previewTrack.waitingLoading);
  848.         playPreviewButtonCanvasGroup.alpha = progressBar.gameObject.activeSelf ? 0 : 1;
  849.  
  850.         if (model.previewTrack.waitingLoading)
  851.         {
  852.             progressBar.StartIndeterminate();
  853.         }
  854.     }
  855.  
  856.     public void SetPlayButtonIcon(PackButtonModel model)
  857.     {
  858.         if (!model.hasPreview)
  859.         {
  860.             packPreviewButtonGO.gameObject.SetActive(false);
  861.             packPreviewTextGO.gameObject.SetActive(false);
  862.             return;
  863.         }
  864.  
  865.         packPreviewButtonGO.gameObject.SetActive(true);
  866.         packPreviewTextGO.gameObject.SetActive(true);
  867.  
  868.         if (model.previewTrackPlaying)
  869.         {
  870.             playPreviewIcon.SetImage(pauseIcon);
  871.         }
  872.         else
  873.         {
  874.             playPreviewIcon.SetImage(playIcon);
  875.         }
  876.     }
  877.  
  878.     public void ChangeIncludeSwitchVisibility(PackButtonModel model)
  879.     {
  880.         buyButton.gameObject.SetActive(!model.aviable);
  881.         includeSwitch.gameObject.SetActive(model.aviable);
  882.     }
  883.  
  884.     public void ChangeIncludeSwitchStatus(bool isOn)
  885.     {
  886.         includeSwitch.toggle.isOn = isOn;
  887.     }
  888.  
  889.     public void UpdateViews(PackButtonModel model, JamPacksParams _params = null)
  890.     {
  891.         if (packStateGO != null)
  892.             packStateGO.gameObject.SetActive(!model.IsDirectory);
  893.         if (dirStateGO != null)
  894.             dirStateGO.gameObject.SetActive(model.IsDirectory);
  895.  
  896.         if (model.IsDirectory)
  897.         {
  898.             if (model.children != null)
  899.             {
  900.                 dirCount.text = model.children.Length.ToString();
  901.             }
  902.  
  903.             dirLabel.text = $"CATEGORY {model.title.Replace("Indoe rock", "Indie rock")}";
  904.  
  905.             dirIcon.SetImage(model.expanded
  906.                                  ? dirExpandLessIcon
  907.                                  : dirExpandMoreIcon);
  908.         }
  909.         else
  910.         {
  911.             packTitle.text = model.title;
  912.             packDescText.text = model.Description;
  913.             packImage.sprite = model.bg;
  914.             includeSwitch.toggleOnLabel = includeSwitch.toggleOffLabel = I2.Loc.LocalizationManager.GetTranslation("Common/Include_in_playlist");
  915.  
  916.             if (_params?.packsTracksAmount.Keys.ElementAtOrDefault(model.id) != null)
  917.             {
  918.                 tracksCount.text = _params.packsTracksAmount[model.id].ToString() + " " + I2.Loc.LocalizationManager.GetTranslation("Common/Tracks");
  919.             }
  920.  
  921.             if (_params?.packsTracksDuration.Keys.ElementAtOrDefault(model.id) != null)
  922.             {
  923.                 timeCount.text = _params.packsTracksDuration[model.id].ToString() + I2.Loc.LocalizationManager.GetTranslation("Common/m");
  924.             }
  925.  
  926.             SetPlayButtonIcon(model);
  927.  
  928.             if (packDescGO.gameObject.activeSelf != model.descExpanded)
  929.             {
  930.                 UpdateExpandedState(model.descExpanded);
  931.                 model.HasPendingSizeChange = true;
  932.             }
  933.  
  934.             progressBar.transform.position = progressBarTMP.transform.position;
  935.             ChangeElementLoadingState(model);
  936.             ChangeIncludeSwitchVisibility(model);
  937.             ChangeIncludeSwitchStatus(model.included);
  938.         }
  939.  
  940.         _Model = model;
  941.         _Params = _params;
  942.     }
  943. }
  944.  
  945. public class PackButtonModel
  946. {
  947.     public int id;
  948.     public bool aviable;
  949.     public bool hasPreview;
  950.     public string title;
  951.     public string name;
  952.     public Sprite bg;
  953.     public Sprite bg_mini;
  954.     public float price;
  955.     public string priceLocalizedString;
  956.     public TrackButtonModel previewTrack;
  957.     public bool previewTrackPlaying = false;
  958.     public bool included;
  959.     public bool showInList;
  960.  
  961.     private string _description;
  962.  
  963.     public bool IsDirectory
  964.     {
  965.         get { return children != null; }
  966.     }
  967.  
  968.     public string Description
  969.     {
  970.         get { return _description; }
  971.         set
  972.         {
  973.             if (_description != value)
  974.             {
  975.                 _description = value;
  976.             }
  977.         }
  978.     }
  979.  
  980.     public bool descExpanded = false;
  981.     public bool HasPendingSizeChange { get; set; }
  982.  
  983.     public PackButtonModel()
  984.     {
  985.         HasPendingSizeChange = true;
  986.     }
  987.  
  988.     public PackButtonModel[] children;
  989.     public bool expanded;
  990. }
  991.  
  992. [Serializable]
  993. public class JamPacksParams : BaseParamsWithPrefabAndData<PackButtonModel>
  994. {
  995.     public class JamPacksPlaylistUpdateEvent : UnityEvent<int>
  996.     {
  997.     }
  998.  
  999.     public JamPacksPlaylistUpdateEvent OnPacksUpdated = new JamPacksPlaylistUpdateEvent();
  1000.     public UnityEvent OnSortModels = new UnityEvent();
  1001.  
  1002.     public TracksLibrary tracksLibrary;
  1003.     public PacksLibrary packsLibrary;
  1004.     public Dictionary<int, int> packsTracksAmount = new Dictionary<int, int>();
  1005.     public Dictionary<int, int> packsTracksDuration = new Dictionary<int, int>();
  1006.     public Transform content;
  1007.     private string lastPreviewFilename;
  1008.     public JamPacksScrollRectItemsAdapter Adapter;
  1009.     private bool _pricesIninitilized = false;
  1010.  
  1011.     public bool PricesIninitilized
  1012.     {
  1013.         get { return _pricesIninitilized; }
  1014.         set { _pricesIninitilized = value; }
  1015.     }
  1016.  
  1017.     private List<Pack> _filteredPacks = new List<Pack>();
  1018.  
  1019.     public List<Pack> FilteredPacks
  1020.     {
  1021.         get { return _filteredPacks; }
  1022.     }
  1023.  
  1024.     public string currentGroupField = "Style";
  1025.     public bool GroupPacks = false;
  1026.  
  1027.     private Dictionary<string, string> _packsCategories = new Dictionary<string, string>();
  1028.  
  1029.     public Dictionary<string, string> PacksCategories
  1030.     {
  1031.         get { return _packsCategories; }
  1032.     }
  1033.  
  1034.     private Dictionary<string, List<Pack>> _packsGrouped = new Dictionary<string, List<Pack>>();
  1035.  
  1036.     public Dictionary<string, List<Pack>> PacksGrouped
  1037.     {
  1038.         get { return _packsGrouped; }
  1039.     }
  1040.  
  1041.     public PackButtonModel hierarchyRootNode;
  1042.     public List<PackButtonModel> flattenedVisibleHierarchy = new List<PackButtonModel>();
  1043.  
  1044.     public void InitPacks()
  1045.     {
  1046.         _filteredPacks = new List<Pack>(packsLibrary.packs.Where(el => el.showInList));
  1047.  
  1048.         foreach (var pack in packsLibrary.packs)
  1049.         {
  1050.             int tracksAmount = tracksLibrary.tracks.Where(el => el.pack.ToLower() == pack.name.ToLower()).ToList().Count;
  1051.             if (!packsTracksAmount.ContainsKey(pack.id))
  1052.             {
  1053.                 packsTracksAmount.Add(pack.id, tracksAmount);
  1054.             }
  1055.         }
  1056.  
  1057.         foreach (var pack in packsLibrary.packs)
  1058.         {
  1059.             float packDuration = tracksLibrary.tracks.Where(el => el.pack.ToLower() == pack.name.ToLower()).Sum(el => el.lenght);
  1060.             if (!packsTracksDuration.ContainsKey(pack.id))
  1061.             {
  1062.                 packsTracksDuration.Add(pack.id, (int) (packDuration / 60));
  1063.             }
  1064.         }
  1065.  
  1066.         currentGroupField = "Style";
  1067.         SetPacksGrouped(currentGroupField);
  1068.     }
  1069.  
  1070.     public void SetPacksGrouped(string field)
  1071.     {
  1072.         currentGroupField = field;
  1073.  
  1074.         _packsCategories.Clear();
  1075.         _packsGrouped.Clear();
  1076.  
  1077.         switch (currentGroupField)
  1078.         {
  1079.             case "Style":
  1080.                 GroupPacksByStyle();
  1081.                 break;
  1082.         }
  1083.     }
  1084.  
  1085.     private void GroupPacksByStyle()
  1086.     {
  1087.         /*Debug.Log("----------");
  1088.         foreach (var style in GetPacksStylesFromFiltered())
  1089.         {
  1090.             Debug.Log(style);
  1091.         }
  1092.  
  1093.         Debug.Log("----------");
  1094.  
  1095.         Debug.Log("----------");
  1096.         foreach (var style in AppMenuEventsHandler.Instance.CachedStylesTranslations)
  1097.         {
  1098.             Debug.Log(style.Key + "|" + style.Value);
  1099.         }
  1100.         */
  1101.  
  1102.         foreach (var style in GetPacksStylesFromFiltered())
  1103.         {
  1104.             //Debug.Log(style);
  1105.             //_tracksCategories.Add(LocalizationManager.GetTranslation("Common/Styles_" + style), style);
  1106.             _packsCategories.Add(AppMenuEventsHandler.Instance.CachedStylesTranslations[style.ToLower().Replace(" ", "_").Replace("'", "_")], style);
  1107.         }
  1108.  
  1109.         foreach (var style in _packsCategories)
  1110.         {
  1111.             if (_filteredPacks.Any(el => el.Style.ToLower() == style.Value.ToLower()))
  1112.                 _packsGrouped.Add(style.Key, _filteredPacks.FindAll(el => el.Style.ToLower() == style.Value.ToLower()));
  1113.  
  1114.             //Тут у нас все паки кроме бесплатного, потому что у него нет стиля
  1115.         }
  1116.  
  1117.  
  1118.         Debug.Log("----------");
  1119.         foreach (var el in _packsGrouped)
  1120.         {
  1121.             Debug.Log(el.Key + "|" + el.Value.Count);
  1122.         }
  1123.     }
  1124.  
  1125.     private SortedSet<string> GetPacksStylesFromFiltered()
  1126.     {
  1127.         SortedSet<string> styles = new SortedSet<string>();
  1128.         for (int i = 0; i < _filteredPacks.Count; i++)
  1129.         {
  1130.             if (_filteredPacks[i].showInList && !_filteredPacks[i].Style.IsNullOrWhitespace())
  1131.             {
  1132.                 styles.Add(_filteredPacks[i].Style);
  1133.             }
  1134.         }
  1135.  
  1136.         return styles;
  1137.     }
  1138.  
  1139.     private void OnPreviewTrackStartLoading(PackButtonModel model)
  1140.     {
  1141.         model.previewTrack.loadingValue = 0;
  1142.     }
  1143.  
  1144.     public void ChangePacksPrices()
  1145.     {
  1146.         if (_pricesIninitilized)
  1147.             return;
  1148.  
  1149.         if (!Purchaser.Instance.Initialized)
  1150.             return;
  1151.  
  1152.         _pricesIninitilized = true;
  1153.  
  1154.         foreach (var item in Purchaser.Instance.Controller.products.all)
  1155.         {
  1156.             PackProduct packProduct = null;
  1157.             packProduct = Purchaser.Instance.NC_Products_Packs.Find(el => el.Name == item.definition.id);
  1158.             if (packProduct == null)
  1159.                 continue;
  1160.  
  1161.             if (!packsLibrary.packs.Exists(el => el.id == packProduct.PackID))
  1162.                 continue;
  1163.  
  1164.             packsLibrary.packs.Find(el => el.id == packProduct.PackID).Price = (float) item.metadata.localizedPrice;
  1165.             packsLibrary.packs.Find(el => el.id == packProduct.PackID).PriceLocalized = item.availableToPurchase
  1166.                                                                                             ? item.metadata.localizedPriceString
  1167.                                                                                             : I2.Loc.LocalizationManager.GetTranslation("Common/product_not_aviable");
  1168.         }
  1169.  
  1170.         InitPacks();
  1171.         OnPacksUpdated.Invoke(_filteredPacks.Count);
  1172.     }
  1173.  
  1174.     private void OnPreviewTrackLoadingProgress(PackButtonModel model, float progress)
  1175.     {
  1176.         model.previewTrack.waitingLoading = false;
  1177.         model.previewTrack.loaded = false;
  1178.         model.previewTrack.loading = true;
  1179.         model.previewTrack.loadingValue = progress;
  1180.     }
  1181.  
  1182.     private void ChangeAllPacksIncludedStatus(bool status)
  1183.     {
  1184.         for (int i = 0; i < Adapter.GetVHHolders().Values.Count(el => el.aviable); i++)
  1185.         {
  1186.             if (Adapter.GetVHHolders().Values.ElementAt(i).aviable)
  1187.             {
  1188.                 Adapter.GetVHHolders().Values.ElementAt(i).included = status;
  1189.                 Adapter.GetVHHolders().Keys.ElementAt(i).includeSwitch.toggle.isOn = status;
  1190.             }
  1191.         }
  1192.  
  1193.         foreach (var packModel in Data.Where(el => el.aviable))
  1194.         {
  1195.             packModel.included = status;
  1196.         }
  1197.  
  1198.         foreach (var pack in packsLibrary.packs.Where(el => el.aviable))
  1199.         {
  1200.             pack.included = status;
  1201.         }
  1202.  
  1203.         EventManager.TriggerEvent("Playlist_FilterAfterPacksChanges");
  1204.     }
  1205.  
  1206.     public void IncludeAllPacks()
  1207.     {
  1208.         ChangeAllPacksIncludedStatus(true);
  1209.     }
  1210.  
  1211.     public void OnPackPurchased(Dictionary<string, string> paramsDictionary)
  1212.     {
  1213.         string packIdStr = "-1";
  1214.         int packId = -1;
  1215.  
  1216.         paramsDictionary.TryGetValue("packId", out packIdStr);
  1217.         packId = Int32.Parse(packIdStr);
  1218.  
  1219.         if (Debug.isDebugBuild)
  1220.             Debug.Log($"OnPackPurchased for {packId}");
  1221.  
  1222.         if (packId > 1)
  1223.         {
  1224.             ChangePackAviableStatus(packId, true);
  1225.         }
  1226.     }
  1227.  
  1228.     private void ChangePackAviableStatus(int packId, bool aviable)
  1229.     {
  1230.         if (packsLibrary.packs.Exists(el => el.id == packId))
  1231.         {
  1232.             packsLibrary.packs.Find(el => el.id == packId).aviable = aviable;
  1233.             Data.Find(el => el.id == packId).aviable = aviable;
  1234.  
  1235.             EventManager.TriggerEvent("Playlist_FilterAfterPacksChanges");
  1236.         }
  1237.     }
  1238.  
  1239.     public void FilterPacksByStyle(Dictionary<string, string> paramsDictionary)
  1240.     {
  1241.         string selectedOptions = "";
  1242.         paramsDictionary.TryGetValue("selectedOptions", out selectedOptions);
  1243.  
  1244.         string[] filterOptions = selectedOptions?.Split(new string[] {","}, StringSplitOptions.None);
  1245.  
  1246.         if (filterOptions == null)
  1247.             return;
  1248.  
  1249.         foreach (var pack in packsLibrary.packs)
  1250.         {
  1251.             pack.showInList = pack.id == 1 || filterOptions.Contains(pack.Style);
  1252.         }
  1253.  
  1254.         _filteredPacks = packsLibrary.packs.Where(el => el.showInList).ToList();
  1255.         OnPacksUpdated.Invoke(_filteredPacks.Count);
  1256.     }
  1257.  
  1258.     public void ExcludeAllPacks()
  1259.     {
  1260.         ChangeAllPacksIncludedStatus(false);
  1261.     }
  1262.  
  1263.     public void ResetAllPacksPlayButtons()
  1264.     {
  1265.         if (Adapter == null)
  1266.             return;
  1267.  
  1268.         foreach (var packModel in Adapter.GetVHHolders().Values)
  1269.         {
  1270.             packModel.previewTrackPlaying = false;
  1271.         }
  1272.  
  1273.         lastPreviewFilename = String.Empty;
  1274.     }
  1275.  
  1276.     private async void OnTrackLoaded(PackButtonModel model, string fileName, bool fromCache)
  1277.     {
  1278.         if (!fromCache)
  1279.         {
  1280.             UpdateDataCachedState(model);
  1281.         }
  1282.         else
  1283.         {
  1284.             bool newPreviewTrack = fileName != lastPreviewFilename;
  1285.             ClipPlayer.Instance.PlayPreview(fileName, model.previewTrack, () => {
  1286.                 ResetAllPacksPlayButtons();
  1287.                 model.previewTrackPlaying = true;
  1288.                 lastPreviewFilename = fileName;
  1289.             }, () => { model.previewTrackPlaying = !model.previewTrackPlaying; }, newPreviewTrack);
  1290.         }
  1291.  
  1292.         model.previewTrack.waitingLoading = false;
  1293.         model.previewTrack.loading = false;
  1294.         model.previewTrack.loaded = true;
  1295.     }
  1296.  
  1297.     private void OnTrackLoadingError(PackButtonModel model, string errorMsg)
  1298.     {
  1299.         ToastManager.Show(errorMsg);
  1300.         model.previewTrack.waitingLoading = false;
  1301.         model.previewTrack.loading = false;
  1302.         model.previewTrack.loaded = false;
  1303.     }
  1304.  
  1305.     private void UpdateDataCachedState(PackButtonModel model)
  1306.     {
  1307.         if (Data.Exists(el => el.id == model.id))
  1308.         {
  1309.             Data.Find(el => el.id == model.id).previewTrack.cached = model.previewTrack.cached;
  1310.         }
  1311.     }
  1312.  
  1313.     private void OnStartStreamingPreviewTrackAssetsLoading(TrackButtonModel model)
  1314.     {
  1315.         model.waitingLoading = true;
  1316.     }
  1317.  
  1318.     private void OnStreamingPreviewTrackAssetsLoaded(PackButtonModel model)
  1319.     {
  1320.         bool newPreviewTrack = model.previewTrack.clipName != lastPreviewFilename;
  1321.         ClipPlayer.Instance.PlayPreview(null, model.previewTrack, () => {
  1322.             ResetAllPacksPlayButtons();
  1323.             model.previewTrackPlaying = true;
  1324.             lastPreviewFilename = model.previewTrack.clipName;
  1325.         }, () => { model.previewTrackPlaying = !model.previewTrackPlaying; }, newPreviewTrack, true);
  1326.  
  1327.         model.previewTrack.waitingLoading = false;
  1328.         model.previewTrack.loading = false;
  1329.         model.previewTrack.loaded = true;
  1330.     }
  1331.  
  1332.     public void PlayStreamingPreviewTrack(PackButtonModel model)
  1333.     {
  1334.         if (Application.internetReachability == NetworkReachability.NotReachable)
  1335.         {
  1336.             OnTrackLoadingError(model, I2.Loc.LocalizationManager.GetTranslation("Errors/NetworkReachability_error"));
  1337.         }
  1338.  
  1339.         bool newPreviewTrack = model.previewTrack.clipName != lastPreviewFilename;
  1340.         if (newPreviewTrack && Application.internetReachability != NetworkReachability.NotReachable)
  1341.         {
  1342.             model.previewTrack.waitingLoading = true;
  1343.         }
  1344.  
  1345.         if (Application.internetReachability != NetworkReachability.NotReachable
  1346.             || (Application.internetReachability == NetworkReachability.NotReachable && !newPreviewTrack && ClipPlayer.Instance.isPlayingPreview))
  1347.         {
  1348.             ClipPlayer.Instance.PlayPreview(null, model.previewTrack, () => {
  1349.                 ResetAllPacksPlayButtons();
  1350.                 model.previewTrackPlaying = true;
  1351.                 lastPreviewFilename = model.previewTrack.clipName;
  1352.  
  1353.                 model.previewTrack.waitingLoading = false;
  1354.                 model.previewTrack.loading = false;
  1355.                 model.previewTrack.loaded = true;
  1356.             }, () => { model.previewTrackPlaying = !model.previewTrackPlaying; }, newPreviewTrack, true);
  1357.         }
  1358.  
  1359.         /*TrackLoadingManager.Instance.StartLoadingStreamingTrackAssets(model.previewTrack,
  1360.                                                                       () => OnStartStreamingPreviewTrackAssetsLoading(model.previewTrack),
  1361.                                                                       () => { OnStreamingPreviewTrackAssetsLoaded(model); },
  1362.                                                                       errorMsg => OnTrackLoadingError(model, errorMsg)
  1363.                                                                      );*/
  1364.     }
  1365.  
  1366.     public void PlayPreviewTrack(PackButtonModel model)
  1367.     {
  1368.         TrackLoadingManager.Instance.StartLoadingTrack(model.previewTrack,
  1369.                                                        () => OnPreviewTrackStartLoading(model),
  1370.                                                        progress => OnPreviewTrackLoadingProgress(model, progress),
  1371.                                                        (fileName, fromCache) => { OnTrackLoaded(model, fileName, fromCache); },
  1372.                                                        errorMsg => OnTrackLoadingError(model, errorMsg)
  1373.                                                       );
  1374.     }
  1375.  
  1376.     public async void DownloadPreviewTrack(PackButtonModel model)
  1377.     {
  1378.         if (!model.previewTrack.loaded && !model.previewTrack.loading && !model.previewTrack.waitingLoading)
  1379.         {
  1380.             model.previewTrack.waitingLoading = true;
  1381.             TrackLoadingManager.TrackState trackState = await TrackLoadingManager.Instance.StartLoadingTrack(model.previewTrack,
  1382.                                                                                                              () => OnPreviewTrackStartLoading(model),
  1383.                                                                                                              progress => OnPreviewTrackLoadingProgress(model, progress),
  1384.                                                                                                              (fileName, fromCache) => {
  1385.                                                                                                                  model.previewTrack.cached = true;
  1386.                                                                                                                  OnTrackLoaded(model, fileName, fromCache);
  1387.                                                                                                              }
  1388.                                                                                                              ,
  1389.                                                                                                              errorMsg => OnTrackLoadingError(model, errorMsg),
  1390.                                                                                                              true
  1391.                                                                                                             );
  1392.  
  1393.             switch (trackState)
  1394.             {
  1395.                 /*case TrackLoadingManager.TrackState.Loading:
  1396.                     model.loading = true;
  1397.                     break;*/
  1398.                 case TrackLoadingManager.TrackState.WaitingForLoading:
  1399.                     model.previewTrack.waitingLoading = true;
  1400.                     break;
  1401.                 case TrackLoadingManager.TrackState.LoadingError:
  1402.                     model.previewTrack.waitingLoading = false;
  1403.                     model.previewTrack.loaded = false;
  1404.                     model.previewTrack.loading = false;
  1405.                     break;
  1406.             }
  1407.         }
  1408.     }
  1409. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand