using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Tao.OpenGl;
using WiimoteLib;

namespace Log740
{
    class ExemplePlaneWii : AbstractPlaneExemple
    {
        private WiiInput wm; // Controle de Wiimote

        private Quaternion quat_wii = Quaternion.Identity(); // quaternion de la rotation du wiimote

        public ExemplePlaneWii()
        {
            wm = new WiiInput(20, Quaternion.Identity(), false);
            wm.ButtonPress += wm_ButtonEventHandler;
            wm.ButtonDepress += wm_ButtonEventHandler;
            wm.SetLEDs(true, false, false, false);
        }

        protected override void Cleanup()
        {
            wm.Disconnect();
        }

        private void wm_ButtonEventHandler(object sender, WiimoteButtonEvent args)
        {
            if (args.Pressed)
            {
                // Quand le bouton Home est appuye, remettre la position et orientation a zero
                if (args.ButtonType == BUTTON_TYPE.HOME_BUTTON)
                {
                    ResetPosition();
                }
                // Quand le bouton A est appuye, tire un projectile
                else if (args.ButtonType == BUTTON_TYPE.A_BUTTON)
                {
                    Shoot();
                }
            }

            if (args.ButtonType == BUTTON_TYPE.Z_BUTTON)
            {
                pointing = args.Pressed;

                // Quand Z est relache, ramene le curseur
                if (pointing == false)
                {
                    ResetCrosshair();
                }
            }
        }

        override protected void RefreshScene()
        {
            base.RefreshScene(); // pour Esc -> Close

            wm.DoEvents(); // S'occuper des evenements du wiimote

            // Quitter si le bouton Plus est appuye
            if (wm.Buttons.Plus)
            {
                this.CloseGLWindow();
            }


            // Si Z est appuye, le joystick deplace la mire
            if (wm.Nunchuck.Z)
            {
                if (Math.Abs(wm.Nunchuck.Joystick.X) > WiiInput.JOYSTICK_DEADZONE)
                {
                    crosshair.Location.X += wm.Nunchuck.Joystick.X * 30;
                }

                if (Math.Abs(wm.Nunchuck.Joystick.Y) > WiiInput.JOYSTICK_DEADZONE)
                {
                    crosshair.Location.Y += wm.Nunchuck.Joystick.Y * 30;
                }
            }
            else
            {
                // Sinon, utilise le joystick en Y pour l'acceleration
                speed_forward = wm.Nunchuck.Joystick.Y + 0.5;
            }

            Vecteur3F rot_wii = wm.Rotation.toEuler();

            speed_pitch = rot_wii.X / 10;
            speed_turn = -rot_wii.Z / 20;
            roll = -rot_wii.Z;
        }
    }
}
