﻿using Ashram.Bhajans.Controllers;
using Ashram.Bhajans.Database.Tables;
using System;
using UnityEngine;
using UnityEngine.UI;

namespace Ashram.Bhajans.Views
{
    /// <summary>
    /// @author Mayank Grover 
    /// </summary>

    public class ViewDynamicItemAmritKirtan: View
    {
        public Button ButtonAmritKirtan;
        public Toggle ToggleFavourite;
        public Text TitleMain;

        public Sprite SpriteFavourite;
        public Sprite SpriteNonFavourite;

        public Action OnClickAmritKirtan;
        public Action<bool> OnClickFavourite;

        public TableAmritKirtan dataAmritKirtan { get; private set; }
        private ControllerDynamicItemAmritKirtan controllerKirtan;

        public void UpdateView(TableAmritKirtan data)
        {
            this.dataAmritKirtan = data;
            RecycleController();
            RefreshView();
            CreateController();
        }

        public void RefreshView()
        {
            ToggleFavourite.isOn = dataAmritKirtan.Favourite == 1;
            TitleMain.text = dataAmritKirtan.TitlePunjabi1;
            UpdateFavouriteSprite(dataAmritKirtan.Favourite == 1);
        }

        public void Clear()
        {
            Destroy(gameObject);
        }

        protected override void RegisterClickHandlers()
        {
            base.RegisterClickHandlers();

            ButtonAmritKirtan.onClick.AddListener(() => {
                if (OnClickAmritKirtan != null) OnClickAmritKirtan();
            });

            ToggleFavourite.onValueChanged.AddListener((isFavourite) => {
                UpdateFavouriteSprite(isFavourite);
                if(OnClickFavourite != null) OnClickFavourite(isFavourite);
            });
        }

        private void UpdateFavouriteSprite(bool isFavourite)
        {
            ToggleFavourite.GetComponent<Image>().sprite =
                isFavourite ? SpriteFavourite : SpriteNonFavourite;
        }

        private void CreateController()
        {
            if(controllerKirtan == null) {
                controllerKirtan = new ControllerDynamicItemAmritKirtan();
            }

            controllerKirtan.UpdateData(this);
        }

        private void RecycleController()
        {
            if(controllerKirtan != null) {
                controllerKirtan.Clear();
            }
        }
    }
}
