/*
Copyright (c) 2016 Robert Atkinson

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.

NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.Range;

/**
 * This file provides Telop driving for the 6417 Mechanum Drive Robot.
 * The code is structured as an Iterative OpMode
 *
 * All device access is managed through the HardwareMech class.
 *
 */

@TeleOp(name="6417 Mech Tele", group="Tele")
//@Disabled
public class TeleopMech extends OpMode{

    /* Declare OpMode members. */
    HardwareMech robot       = new HardwareMech();

    boolean clawOpen = false;
    boolean tailDown = false;

    boolean prevTail = false;
    boolean currTail = false;

    boolean prevBumper = false;
    boolean currBumper = false;

    boolean prevX = false;
    boolean currX = false;
    boolean strafeFull = true;

    boolean dpad = false;

    boolean prevB = false;
    boolean currB = false;

    boolean prevLiftReset = false;
    boolean currLiftReset = false;
    boolean liftOverride = false;

    boolean prevScale = false;
    boolean currScale = false;
    boolean isScaling = false;

    /*
     * Code to run ONCE when the driver hits INIT
     */
    @Override
    public void init() {
        /* Initialize the hardware variables.
         * The init() method of the hardware class does all the work here
         */
        robot.define(hardwareMap);

        // Send telemetry message to signify robot waiting;
        telemetry.addData("Say", "Hello Driver");
    }

    /*
     * Code to run REPEATEDLY after the driver hits INIT, but before they hit PLAY
     */
    @Override
    public void init_loop() {

        /*// bPrevState and bCurrState represent the previous and current state of the button.
        boolean bPrevState = false;
        boolean bCurrState = false;

        // check the status of the x button on either gamepad.
        bCurrState = gamepad1.x;

        // check for button state transitions.
        if ((bCurrState == true) && (bCurrState != bPrevState))  {

            // button is transitioning to a pressed state.
            redTeam = !redTeam;
        }

        // update previous state variable.
        bPrevState = bCurrState;*/

        // Display the light level while we are waiting to start
        telemetry.addData("Status", "Ready to Start");
        telemetry.update();

    }

    /*
     * Code to run ONCE when the driver hits PLAY
     */
    @Override
    public void start() {
        robot.moveServos();
    }

    /*
     * Code to run REPEATEDLY after the driver hits PLAY but before they hit STOP
     */
    @Override
    public void loop() {

        double LFspeed;
        double LBspeed;
        double RFspeed;
        double RBspeed;

        double leftY = gamepad1.left_stick_y;
        double leftX = gamepad1.left_stick_x;
        double rightX = gamepad1.right_stick_x;
        double rightY = gamepad1.right_stick_y;


        //toggle scaling for more precise low power movements
        currScale = gamepad1.left_stick_button;
        if(currScale && currScale != prevScale){
            isScaling = !isScaling;
        }
        prevScale = currScale;

        //TODO: cube for more precision?
        if(isScaling){
            leftY = robot.scaleInput(leftY);
            leftX = robot.scaleInput(leftX);
            rightX = robot.scaleInput(rightX);
            rightY = robot.scaleInput(rightY);
        }


        //switch control schemes
        currX = gamepad1.x;
        if(currX && currX != prevX){
            strafeFull = !strafeFull;
        }
        prevX = currX;


        if(strafeFull){
            // Run wheels in full strafe mode (note: The joystick goes negative when pushed forwards, so negate it)
            LFspeed = -leftY + leftX;
            LBspeed = -leftY - leftX;
            RFspeed = -rightY - rightX;
            RBspeed = -rightY + rightX;
        } else {
            // Run wheels in more simplistic drone config
            LFspeed = -rightY + rightX + leftX;
            LBspeed = -rightY - rightX + leftX;
            RFspeed = -rightY - rightX - leftX;
            RBspeed = -rightY + rightX - leftX;
        }

        //LFspeed = Range.scale(LFspeed, -1, 1, -.5, .5);
        //LBspeed = Range.scale(LBspeed, -1, 1, -.3, .3);
        //RFspeed = Range.scale(RFspeed, -1, 1, -.5, .5);
        //RBspeed = Range.scale(RBspeed, -1, 1, -.3, .3);

        LFspeed = Range.clip(LFspeed, -1, 1);
        LBspeed = Range.clip(LBspeed, -1, 1);
        RFspeed = Range.clip(RFspeed, -1, 1);
        RBspeed = Range.clip(RBspeed, -1, 1);


        double strafeSpeed = 1;
        if(isScaling)
            strafeSpeed = 0.5;

        if(gamepad1.dpad_left){
            LFspeed = -strafeSpeed;
            RFspeed = strafeSpeed;
            LBspeed = strafeSpeed;
            RBspeed = -strafeSpeed;
        } else if(gamepad1.dpad_right){
            LFspeed = strafeSpeed;
            RFspeed = -strafeSpeed;
            LBspeed = -strafeSpeed;
            RBspeed = strafeSpeed;
        }

        robot.leftFront.setPower(LFspeed);
        robot.rightFront.setPower(RFspeed);
        robot.leftRear.setPower(LBspeed);
        robot.rightRear.setPower(RBspeed);

        telemetry.addData("Left Front", LFspeed);
        telemetry.addData("Left Rear", LBspeed);
        telemetry.addData("Right Front", RFspeed);
        telemetry.addData("Right Rear", RBspeed);


        currBumper = gamepad1.right_bumper;

        //control claw
        //trigger closes claw
        if (gamepad1.right_trigger>0.1 && robot.clawLeft.getPosition() < robot.CLAW_LEFT_MAX) {
            robot.clawRight.setPosition(robot.clawRight.getPosition() + .02);
            robot.clawLeft.setPosition(robot.clawLeft.getPosition() + .02);
            clawOpen = true;
        } else if (currBumper && currBumper != prevBumper){
            //first bumber click = release block
            //second bumper click = fully open claws
            if(clawOpen){
                robot.clawLeft.setPosition(robot.CLAW_LEFT_INIT);
                robot.clawRight.setPosition(robot.CLAW_RIGHT_INIT);
                clawOpen = false;
            } else {
                robot.clawLeft.setPosition(robot.CLAW_LEFT_MIN);
                robot.clawRight.setPosition(robot.CLAW_RIGHT_MIN);
            }
        }

        if (gamepad1.right_trigger>0.1){
            robot.leftBotWheel.setPower(.85);
            robot.rightBotWheel.setPower(.85);
            robot.leftTopWheel.setPower(.8); //.85?
            robot.rightTopWheel.setPower(.8);
        } else {
            robot.leftBotWheel.setPower(0);
            robot.rightBotWheel.setPower(0);
            robot.leftTopWheel.setPower(0);
            robot.rightTopWheel.setPower(0);
        }

        prevBumper = currBumper;

        /*currB = gamepad1.b;
        if(currB && currB != prevB && robot.clawLeft.getPosition() < .8){
            robot.clawLeft.setPosition(robot.CLAW_LEFT_INIT);
            robot.waitForTick(500);
            robot.clawRight.setPosition(robot.CLAW_RIGHT_INIT);
        }
        prevB = currB;*/

        if(gamepad1.b){
            robot.clawLeft.setPosition(robot.CLAW_LEFT_INIT);
            robot.clawRight.setPosition(robot.CLAW_RIGHT_INIT);
            clawOpen = false;
        }


        currTail = gamepad1.y;
        //control tail up/down with Y button
        if(currTail && currTail != prevTail){
            if(tailDown) {
                robot.tailServoY.setPosition(robot.TAIL_UP);
                tailDown = false;
            }else {
                robot.tailServoY.setPosition(robot.TAIL_DOWN);
                tailDown = true;
            }
        }
        prevTail = currTail;


        currLiftReset = gamepad1.right_stick_button;
        if(currLiftReset && currLiftReset != prevLiftReset){

            if(!liftOverride) {
                robot.liftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
            }else {
                robot.liftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
                robot.liftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
            }

            liftOverride = !liftOverride;
        }
        prevLiftReset = currLiftReset;


        //control lift with left trigger/bumper
        //code limited to prevent over-running
        if(gamepad1.left_trigger>0.1) {

            robot.liftMotor.setTargetPosition(2550);
            robot.liftMotor.setPower(robot.LIFT_UP_POWER);
            dpad = false;

        } else if(gamepad1.left_bumper) {

            robot.liftMotor.setTargetPosition(-50);
            robot.liftMotor.setPower(robot.LIFT_DOWN_POWER);
            dpad = false;

        } else if (!dpad)
            robot.liftMotor.setPower(0);

        if(gamepad1.dpad_up){
            robot.liftMotor.setTargetPosition(2550);
            robot.liftMotor.setPower(robot.LIFT_UP_POWER);
            dpad = true;
        } else if(gamepad1.dpad_down){
            robot.liftMotor.setTargetPosition(-50);
            robot.liftMotor.setPower(robot.LIFT_DOWN_POWER);
            dpad = true;
        }

        if(dpad && !robot.liftMotor.isBusy()) {
            dpad = false;
        }


        //GAMEPAD 2 CONTROLS

        //scale gamepad 2 joysticks to appropriate values
        double slidePower = -gamepad2.left_stick_y;
        double armPower = -gamepad2.right_stick_y;
        //slidePower = Range.scale(slidePower, -1, 1, robot.SLIDE_IN_POWER, robot.SLIDE_OUT_POWER);
        armPower = Range.scale(armPower, -1, 1, -.01, .01);

        //code limit slider positions
        if(slidePower > 0) {
            robot.slideMotor.setTargetPosition(4550);
            slidePower *= robot.SLIDE_OUT_POWER;
        }else if(slidePower < 0) {
            robot.slideMotor.setTargetPosition(0);
            slidePower *= robot.SLIDE_IN_POWER;
        }

        robot.slideMotor.setPower(slidePower);

        robot.arm.setPosition(Range.clip(armPower+robot.arm.getPosition(), robot.ARM_DOWN, robot.ARM_UP)); //control arm movement speed with joystick


        double armClawPos = robot.armClaw.getPosition();

        //arm claw controls with gamepad 2 right trigger/bumper
        if(gamepad2.right_trigger > 0.1 && armClawPos < robot.ARM_CLOSED) {

            robot.armClaw.setPosition(armClawPos+.01);

        } else if(gamepad2.left_trigger > 0.1 && armClawPos > robot.ARM_OPENED) {

            robot.armClaw.setPosition(armClawPos-.01);

        }

        //send debug info
        telemetry.addData("Strafe Fine Control", strafeFull);
        telemetry.addData("Lift Override", liftOverride);
        telemetry.addData("Scaling", isScaling);
        telemetry.addData("lift", robot.liftMotor.getCurrentPosition());
        telemetry.addData("slide", robot.slideMotor.getCurrentPosition());
        telemetry.addData("slide power", robot.slideMotor.getPower());
        telemetry.addData("arm claw", robot.armClaw.getPosition());
        telemetry.update();

    }


    /*
     * Code to run ONCE after the driver hits STOP
     */
    @Override
    public void stop() {
        robot.clawLeft.setPosition(robot.CLAW_LEFT_INIT);
        robot.clawRight.setPosition(robot.CLAW_RIGHT_INIT);
        robot.armClaw.setPosition(robot.ARM_CLOSED -0.2);
    }

}
