using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Extensions;
using System.Linq;
using System.Collections.Generic;
using Framework.InteractionSystem;
using Framework.Utility;

namespace Project.Player
{
    public class PlayerAnimator : CoreBehaviour
    {
        private Animator animator;
        private Rigidbody rigidbody;
        private Transform visual;
        private int state;
        private float speed;
        private int direction = 1;
        private int lastDirection = 1;
        private Vector3 startScale;

        // Use this for initialization
        protected override void InnerAwake()
        {
            AddActionHandler<PlayerMover.MoveAction>(MoveAnimate);
            this.rigidbody = GetComponent<Rigidbody>();
            this.visual = this.transform.RecursivelyFindChild("Visual");
            this.animator = this.visual.GetComponent<Animator>();
            this.startScale = this.visual.localScale;
        }

        // Update is called once per frame
        protected override void InnerUpdate()
        {
            animator.SetInteger("state", this.state);
            animator.speed = this.speed;
            if (this.direction == 1)
            {
                this.visual.localScale = this.startScale;
            }
            else
            {
                this.visual.localScale = new Vector3(-this.startScale.x, this.startScale.y, this.startScale.z);
            }
        }

        private void MoveAnimate(PlayerMover.MoveAction action)
        {
            if (action.moveVector.magnitude > 0)
            {
                this.state = 3;
                this.speed = this.rigidbody.velocity.magnitude * 0.15f;
            }
            else
            {
                this.state = 1;
                this.speed = this.rigidbody.velocity.magnitude * 0.15f;
            }
            if (action.moveVector.x > 0)
            {
                this.direction = 1;
            }
            else if (action.moveVector.x < 0)
            {
                this.direction = -1;
            }
            else if (action.moveVector.x == 0)
            {
                this.direction = this.lastDirection;
            }
            this.lastDirection = direction;
        }
    }
}