#!/usr/bin/env python3
#Edited Default Code by Nekhil R

import os
import sys
import time
import logging
import json
import random
import threading

from enum import Enum
from agt import AlexaGadget

from ev3dev2.led import Leds
from ev3dev2.sound import Sound
from ev3dev2.motor import OUTPUT_A, OUTPUT_B,LargeMotor, SpeedPercent, MediumMotor

# Set the logging level to INFO to see messages from AlexaGadget
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(message)s')
logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
logger = logging.getLogger(__name__)



class MindstormsGadget(AlexaGadget):
    """
    A Mindstorms gadget that performs movement based on voice commands.
    Two types of commands are supported, directional movement and preset.
    """
    def __init__(self):
        """
        Performs Alexa Gadget initialization routines and ev3dev resource allocation.
        """
        super().__init__()

        # Ev3dev initialization
        self.leds = Leds()
        self.sound = Sound()
        self.large = LargeMotor(OUTPUT_B)
        self.medium = MediumMotor(OUTPUT_A)

    def on_connected(self, device_addr):
        """
        Gadget connected to the paired Echo device.
        :param device_addr: the address of the device we connected to
        """
        self.leds.set_color("LEFT", "GREEN")
        self.leds.set_color("RIGHT", "GREEN")
        logger.info("{} connected to Echo device".format(self.friendly_name))

    def on_disconnected(self, device_addr):
        """
        Gadget disconnected from the paired Echo device.
        :param device_addr: the address of the device we disconnected from
        """
        self.leds.set_color("LEFT", "BLACK")
        self.leds.set_color("RIGHT", "BLACK")
        logger.info("{} disconnected from Echo device".format(self.friendly_name))

    def on_custom_mindstorms_gadget_control(self, directive):
        """
        Handles the Custom.Mindstorms.Gadget control directive.
        :param directive: the custom directive with the matching namespace and name
        """
        try:
            payload = json.loads(directive.payload.decode("utf-8"))
            print("Control payload: {}".format(payload), file=sys.stderr)
            control_type = payload["type"]
            if control_type == "distribute":
                # Expected params: [player]
                print(int(payload["player"]))
                self._distribute(int(payload["player"]))
            if control_type == "give":
                # Expected params: [value]
                print(int(payload["value"]))
                self._give(int(payload["value"]))
        except KeyError:
            print("Missing expected parameters: {}".format(directive), file=sys.stderr)

    def _distribute(self,player:int, is_blocking=False):
        """
        Handles distribute commands from the directive.
        Retrieves the player variable and starts distribution.
        """
        print("Distribute command: ({})".format(player), file=sys.stderr)#Print output
        x=300/player
        n=64/(player+1)
        for i in range(int(n)):
            for j in range(player-1):
                self.medium.on_for_rotations(SpeedPercent(50),-1.5)
                self.medium.on_for_rotations(SpeedPercent(50),1.5)
                self.large.on_for_degrees(5,x)
            x=-x
        
    def _give(self,value:int,is_blocking=False):
        """
        Handles give commands from the directive.
        Give as many as card requested by the user.
        """
       
        print("Give command: ({})".format(value), file=sys.stderr)
        for j in range(value):
            self.medium.on_for_rotations(SpeedPercent(50),-1.5)
            self.medium.on_for_rotations(SpeedPercent(50),1.5)

if __name__ == '__main__':

    gadget = MindstormsGadget()

    # Set LCD font and turn off blinking LEDs
    os.system('setfont Lat7-Terminus12x6')
    gadget.leds.set_color("LEFT", "BLACK")
    gadget.leds.set_color("RIGHT", "BLACK")

    # Startup sequence
    gadget.sound.play_song((('C4', 'e'), ('D4', 'e'), ('E5', 'q')))
    gadget.leds.set_color("LEFT", "GREEN")
    gadget.leds.set_color("RIGHT", "GREEN")

    # Gadget main entry point
    gadget.main()

    # Shutdown sequence
    gadget.sound.play_song((('E5', 'e'), ('C4', 'e')))
    gadget.leds.set_color("LEFT", "BLACK")
    gadget.leds.set_color("RIGHT", "BLACK")
