using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using System;

class Controller
{
    private KeyboardState state = Keyboard.GetState();
    private GraphicsDeviceManager graphics;
    private bool heldUp = false;

    public void init(GraphicsDeviceManager Graphics)
    {
        graphics = Graphics;
    }

    public Vector2 updateWindow(int tileSize, int Spacing, Vector2 Size)
    {
        KeyboardState state = Keyboard.GetState();
        if (state.IsKeyDown(Keys.D) && Size.X < 100)
        {
            Size.X++;
            graphics.PreferredBackBufferWidth = (tileSize + Spacing) * (int)Size.X - Spacing;
        }

        if (state.IsKeyDown(Keys.A) && Size.X > 2)
        {
            Size.X--;
            graphics.PreferredBackBufferWidth = (tileSize + Spacing) * (int)Size.X - Spacing;
        }

        if (state.IsKeyDown(Keys.W) && Size.Y < 20)
        {
            Size.Y++;
            graphics.PreferredBackBufferHeight = (tileSize + Spacing) * (int)Size.Y - Spacing + 300;
        }

        if (state.IsKeyDown(Keys.S) && Size.Y > 2)
        {
            Size.Y--;
            graphics.PreferredBackBufferHeight = (tileSize + Spacing) * (int)Size.Y - Spacing + 300;
        }
        return Size;
    }

    public int controllTileSize(Vector2 Size, int tileSize)
    {
        if (Size.X * tileSize + 5 > GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width)
        {
            tileSize--;
        }
        if (Size.X * tileSize - 5 < GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width && tileSize < 56)
        {
            tileSize++;
        }
        return tileSize;
    }

    public int controllSpeed(int Speed)
    {
        KeyboardState state = Keyboard.GetState();
        if (state.IsKeyDown(Keys.Right) && Speed < 350)
        {
            Speed++;
        }

        if (state.IsKeyDown(Keys.Left) && Speed > 0)
        {
            Speed--;
        }

        return Speed;
    }

    public tractorPositionCorrector controllTractorSpeed(float tractorSpeed, Vector2 Position)
    {
        KeyboardState state = Keyboard.GetState();
        tractorPositionCorrector Corrector = new tractorPositionCorrector(Position, tractorSpeed);
        if (!heldUp)
        {
            if (state.IsKeyDown(Keys.Up) && tractorSpeed < 1)
            {
                Corrector.setTractorSpeed(tractorSpeed * 2);
                heldUp = true;
            }
            else if (state.IsKeyDown(Keys.Down) && tractorSpeed > 0.0009765625)
            {
                Corrector.setTractorSpeed(tractorSpeed / 2);
                heldUp = true;
            }
        }
        else if (heldUp && !(state.IsKeyDown(Keys.Down) || state.IsKeyDown(Keys.Up)))
        {
            heldUp = false;
            Corrector.setPosition((float)Math.Ceiling(Position.X), (float)Math.Ceiling(Position.Y));
        }
        
        return Corrector;
    }
}