using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class ListWrapper
{
    public List<Sprite> Sprites;
}

public class ScrollingBg : TravellingThing {
    public float FRESCURA = 0.05f;
    public float speed = 5;
    public List<ListWrapper> sequentialSprites;

    private float multiplier = 1;
    List<GameObject> spritesList;
    private int currentAct = 0;

	// Use this for initialization
	void Start () {
        CreateSprites(GetComponentInParent<TravelController>().CurrentAct, true);
        Destroy(GetComponent<SpriteRenderer>());
	}

public void CreateSprites(int act,bool force)
{
    if (currentAct == act && !force) return;

    var sprite = GetComponent<SpriteRenderer>();
    if (spritesList != null)
    {
        sprite = spritesList[0].GetComponent<SpriteRenderer>();
        foreach (var s in spritesList) Destroy(s.gameObject);
    }

    var cam = Camera.main;
    float height = cam.orthographicSize;
    float width = height * cam.aspect;
    
    spritesList = new List<GameObject>();

    int next = -1;
	for (int i = Mathf.CeilToInt((width+sprite.bounds.size.x)/sprite.bounds.size.x) ; i>=0 ; i--)
    {
        var go = new GameObject();
        go.transform.parent = transform;
        var goRenderer = go.AddComponent<SpriteRenderer>();

        if (sequentialSprites!=null && sequentialSprites.Count>0)
        {
            next++;
            if (next >= sequentialSprites[act].Sprites.Count) next = 0;
            goRenderer.sprite = sequentialSprites[act].Sprites[sequentialSprites[act].Sprites.Count - next - 1];
        }
        else goRenderer.sprite = sprite.sprite;
            
        spritesList.Add(go);
        Vector3 localPos = new Vector3(goRenderer.bounds.size.x - i * FRESCURA, 0, 0) * i;
        go.transform.localPosition = localPos;
    }
}
	
	// Update is called once per frame
	void Update () {
        foreach (var s in spritesList)
        {
            var position = s.transform.localPosition;
            position.x -= Time.deltaTime * speed * multiplier;
            s.transform.localPosition = position;

            var cam = Camera.main;
            float height = cam.orthographicSize;
            float width = height * cam.aspect;
            var me = s.GetComponent<SpriteRenderer>();
            if (me.bounds.max.x < -width)
            {
                position.x = maxRight(spritesList);
                s.transform.localPosition = position;
            }
        }
	}

    private float maxRight(List<GameObject> spritesList)
    {
        float max = float.NegativeInfinity;
        foreach(var s in spritesList)
        {
            var sprite = s.GetComponent<SpriteRenderer>();
            max = Mathf.Max(sprite.bounds.max.x + sprite.bounds.size.x/2,max);
        }
        return max - FRESCURA;
    }

    public override void SetMultiplier(float speed)
    {
        multiplier = speed;
    }

}
