// Student Side.

#include "mbed.h"
#include "SDFileSystem.h"
#include "wave_player.h"
#include "game_synchronizer.h"
#include "tank.h"
#include "bullet.h"
#include "globals.h"
#include "playSound.h"

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);

DigitalIn pb_u(p21);                        // Up Button
DigitalIn pb_r(p22);                        // Right Button
DigitalIn pb_d(p23);                        // Down Button
DigitalIn pb_l(p24);                        // Left Button


DigitalOut latch(p15);
DigitalOut enable(p16);
//Cycles through different colors on RGB LED
//SPI spi(p11, p12, p13);


Serial pc(USBTX, USBRX);                    // Serial connection to PC. Useful for debugging!
MMA8452 acc(p28, p27, 100000);              // Accelerometer (SDA, SCL, Baudrate)
uLCD_4DGL uLCD(p9,p10,p30);                 // LCD (tx, rx, reset)
SDFileSystem sd(p5, p6, p7, p8, "sd");      // SD  (mosi, miso, sck, cs)
AnalogOut DACout(p18);                      // speaker
wave_player player(&DACout);                // wav player
Game_Synchronizer sync(PLAYER1);            // Game_Synchronizer (PLAYER)
Timer frame_timer;                          // Timer
//Speaker mySpeaker(p18);
// Global variables go here.

int winner = -1;
int whose_turn = PLAYER1;
int turn = 1;//turn number
int round_num  = 1;//round number
// Ask the user whether to run the game in Single- or Multi-Player mode.
// Note that this function uses uLCD instead of sync because it is only 
// writing to the local (Player1) lcd. Sync hasn't been initialized yet,
// so you can't use it anyway. For the same reason, you must access
// the buttons directly e.g. if( !pb_r ) { do something; }.

// return MULTI_PLAYER if the user selects multi-player.
// return SINGLE_PLAYER if the user selects single-player.



//RGB function
//void RGB_LED(int red, int green, int blue) {
//        if ((red==255)&&(green==0)&&(blue==0))
//        {spi.write(0xF800);}
//        else if ((red==0)&&(green==0)&&(blue==255))
//        {spi.write(0x001F);}
//        else if ((red==0)&&(green==0)&&(blue==0))
//        {spi.write( 0x0000);}
//}

int game_menu(int *life) {
    int mode;
    uLCD.baudrate(BAUD_3000000);
    uLCD.media_init();
    uLCD.set_sector_address(0x0000, 0x0000);
    uLCD.display_image(0,0);
    playSound("/sd/wavfiles/begin.wav");
    uLCD.textbackground_color(BLACK);
    uLCD.filled_rectangle(0,0,128,128, BLACK);
    // the locate command tells the screen where to place the text.
    uLCD.locate(3,3);
    uLCD.printf("Single-player");
    //uLCD.locate(3,5);
    //uLCD.printf("Multiplayer");

    // Button Example:
    // Use !pb_r to access the player1 right button value.
    
    int old_pb_r;
    int new_pb_r;
    int old_pb_d;
    int new_pb_d;
    int old_pb_l;
    int new_pb_l;
    // Eventually you should return SINGLE_PLAYER or MULTI_PLAYER
    // depending on the user's choice.
    while(1){ 
    new_pb_r = pb_r;
    new_pb_l = pb_l;
    //RGB_LED(255,0,0);
//        if((new_pb_r==0) && (old_pb_r==1)) {
//            mode = MULTI_PLAYER;
//            //playSound("/sd/wavfiles/button1.wav");
//            //PlayNote(300.0,0.25,0.1);
//            break;
//         }else 
         if((new_pb_l==0) && (old_pb_l==1)){
            mode = SINGLE_PLAYER;
            //playSound("/sd/wavfiles/button2.wav");
            //PlayNote(400.0,0.25,0.1);
            break;
        }
    old_pb_r = new_pb_r;
    old_pb_l = new_pb_l;    
    }
    uLCD.textbackground_color(BLACK);
    uLCD.filled_rectangle(0,0,128,128, BLACK);
    // the locate command tells the screen where to place the text.
    uLCD.locate(3,2);
    uLCD.printf("Easy");
    uLCD.locate(3,4);
    uLCD.printf("Medium");
    uLCD.locate(3,6);
    uLCD.printf("Hard");
    //RGB_LED(0,0,0);
    
    //extended menu with three option: easy,medium,hard
    while(1){
    //RGB_LED(0,0,0);
    new_pb_r = pb_r;
    new_pb_d = pb_d;
    new_pb_l = pb_l;
        if((new_pb_l==0) && (old_pb_l==1)) {
            *life = 20;
            //playSound("/sd/wavfiles/button3.wav");
            //mySpeaker.PlayNote(300.0,0.25,0.1);
            break;
         }else if((new_pb_d==0) && (old_pb_d==1)){
            *life = 30;
            //playSound("/sd/wavfiles/button4.wav");
            //mySpeaker.PlayNote(400.0,0.25,0.1);
            break;
        }else if((new_pb_r==0) && (old_pb_r==1)){
            *life = 40;
            //playSound("/sd/wavfiles/button5.wav");
            //mySpeaker.PlayNote(500.0,0.25,0.1);
            break;
        }
        old_pb_r = new_pb_r;
        old_pb_l = new_pb_l;
        old_pb_d = new_pb_d;
        
    }
    
    return mode;
       
}

// Initialize the world map. I've provided a basic map here,
// but as part of the assignment you must create more
// interesting map(s).
// Note that calls to sync.function() will run function()
// on both players' LCDs (assuming you are in multiplayer mode).
// In single player mode, only your lcd will be modified. (Makes sense, right?)
void map_init(int* life) {
    
    // Fill the entire screen with sky blue.
    sync.background_color(SKY_COLOR);
    
    // Call the clear screen function to force the LCD to redraw the screen
    // with the new background color.
    sync.cls();
    
    // Draw the ground in green.
    sync.filled_rectangle(0,0,128,20, GND_COLOR);
    
    // Draw some obstacles. They don't have to be black, 
    // but they shouldn't be the same color as the sky or your tanks.
    // Get creative here. You could use brown and grey to draw a mountain
    // or something cool like that.
    sync.filled_rectangle(59, 20, 69, 60, BLACK);
    
    sync.filled_circle(10,115,4,RED);
    
    sync.filled_rectangle(0, 105, *life, 108, RED);
    sync.filled_rectangle(128-*life, 105, 128, 108, RED);
    // Before you write text on the screens, tell the LCD where to put it.
    sync.filled_rectangle(3,20,6,40, BROWN);
    sync.filled_rectangle(0,40,8,43, TREE_GREEN);
    sync.filled_rectangle(2,43,6,46, TREE_GREEN);
    
    sync.filled_rectangle(125,20,122,40, BROWN);
    sync.filled_rectangle(120,40,128,43, TREE_GREEN);
    sync.filled_rectangle(122,43,126,46, TREE_GREEN);
    sync.locate(0,15);
    
    // Set the text background color to match the sky. Just for looks.
    
    
    // Display the game title.
    char title[10];
    sprintf(title, "Turn %d", turn);
    sync.puts(title, sizeof(title));
    //sync.locate(7,15);
    // turn indicator
    //sync.puts(turn_num, sizeof(turn_num));
    // Flush the draw buffer and execute all the accumulated draw commands.

    sync.update();        
}

// Initialize the game hardware. 
// Call game_menu to find out which mode to play the game in (Single- or Multi-Player)
// Initialize the game synchronizer.
void game_init(int *life) {
    
    led1 = 0; led2 = 0; led3 = 0; led4 = 0;
    
    pb_u.mode(PullUp);
    pb_r.mode(PullUp); 
    pb_d.mode(PullUp);    
    pb_l.mode(PullUp);
    pc.printf("\033[2J\033[0;0H");              // Clear the terminal screen.
    pc.printf("I'm alive! Player 1\n");         // Let us know you made it this far.
    int mode = game_menu(life);
    //uLCD.printf("get back to init");
    sync.init(&uLCD, &acc, &pb_u, &pb_r, &pb_d, &pb_l, mode); // Connect to the other player.
    map_init(life);
    pc.printf("Initialized...\n");              // Let us know you finished initializing.
}

// Display some kind of game over screen which lets us know who won.
// Play a cool sound!
void game_over() {
    while(true){
    sync.textbackground_color(BLACK);
    sync.filled_rectangle(0,0,128,128, BLACK);
    sync.locate(0,8);
    playSound("/sd/wavfiles/end.wav");
    char game_over_str[25];
    sprintf(game_over_str,"Game Over!\n \t Winner %d",winner + 1);
    sync.puts(game_over_str,sizeof(game_over_str));
    sync.update();
    }
}

int round(int round_1,int round_2, int life,Tank* t1, Tank* t2){
    if (round_1 >= 2){
        return PLAYER1;    
    } else if (round_2 >= 2){
        return PLAYER2;    
    } else {

        map_init(&life);
        t1->draw();
        t2->draw();
        return -1;
    }
    
    }

int winner_dec(int life_1,int life_2,int* player1_round, int* player2_round, int life,Tank* t1, Tank* t2){
    if (life_2 <= 0){
        *player1_round = *player1_round+ 1;
        round_num++;
        int play1_round_copy = *player1_round;
        int play2_round_copy = *player2_round;
        return (round(play1_round_copy ,play2_round_copy, life, t1,t2));
    } else if (life_1 <= 0){
        *player2_round = *player2_round + 1;
        round_num++;
        int play1_round_copy = *player1_round;
        int play2_round_copy = *player2_round;
        return (round(play1_round_copy ,play2_round_copy, life,t1,t2));
    } else if (whose_turn == PLAYER1){
        playSound("/sd/wavfiles/lost_life2.wav");
        whose_turn = PLAYER2;
    } else {
        playSound("/sd/wavfiles/lost_life.wav");
        whose_turn = PLAYER1;
    }
        return -1;
}





int main (void) {
    
    int* p1_buttons;
    int* p2_buttons;
    
    float ax1, ay1, az1;
    float ax2, ay2, az2;
    
    int life;
    game_init(&life);
    int life1 = life;
    int life2 = life;
    
    int won_round1 = 0;
    int won_round2 = 0;
    // Create your tanks.
    Tank t1(15, 21, 15, 12, 8, TANK_COLOR1);            // (min_x, min_y, width, height, color)
    Tank t2(101, 21, 101, 12, 8, TANK_COLOR2);         // (min_x, min_y, width, height, color)
    
    // For each tank, create a bullet.
    Bullet b1(&t1);
    Bullet b2(&t2);
    
    //spi.format(16,0);
    //spi.frequency(500000);
    enable=0;
    latch=0;
    //RGB_LED(255,0,0);
    frame_timer.start();
    
    // Your code starts here...
    while(winner == -1) {

        // Get a pointer to the buttons for both sides.
        // From now on, you can access the buttons for player x using
        //
        // px_buttons[U_BUTTON] 
        // px_buttons[R_BUTTON] 
        // px_buttons[D_BUTTON] 
        // px_buttons[L_BUTTON]
        
        p1_buttons = sync.get_p1_buttons();
        p2_buttons = sync.get_p2_buttons();
        
        led1 = p1_buttons[0] ^ p2_buttons[0];
        led2 = p1_buttons[1] ^ p2_buttons[1];
        led3 = p1_buttons[2] ^ p2_buttons[2];
        led4 = p1_buttons[3] ^ p2_buttons[3];

        // Get the accelerometer values.
        sync.get_p1_accel_data(&ax1, &ay1, &az1);
        sync.get_p2_accel_data(&ax2, &ay2, &az2);

        if(whose_turn == PLAYER1) {
            if(p1_buttons[R_BUTTON]) { 
                t1.invisible(); 
            }
            
            // Accelerometer example
            if(ax1 >  ACC_THRESHOLD) { 
                // Move the tank to the right if the accelerometer is tipped far enough to the right.
                 t1.reposition(+1, 0, 0);          
            } else if(ax1 <  -ACC_THRESHOLD){
                t1.reposition(-1, 0, 0);  
            }
            
            if(ay1 >  ACC_THRESHOLD) { 
                // Move the tank to the right if the accelerometer is tipped far enough to the right.
                t1.reposition(0, 0, -PI/10);          
            } else if(ay1 <  -ACC_THRESHOLD){
                t1.reposition(0, 0, PI/10);  
            }
            // Button example
            if(p1_buttons[D_BUTTON]) { 
                b1.shoot(); 
            }
            
            //dt = frame_timer.read()- dt;
            float dt = frame_timer.read();
            //?timer
            int intersection_code = b1.time_step(dt); 
            //?BULLET_NO_COLLISION
            if(intersection_code == BULLET_OFF_SCREEN) { 
                pc.printf("Now it's P2's turn!\n");
                //RGB_LED(0, 0, 255);
                whose_turn = PLAYER2;
                turn++;
                t1.turnback();
                t2.turnback();
                sync.locate(0,15);
                char title[10];
                sprintf(title, "Turn %d", turn);
                sync.puts(title, sizeof(title));
            } else if(sync.pixel_eq(intersection_code, t1.tank_color)) { // If you shot yourself, you lost.
                  pc.printf("c1!\n");
                //RGB_LED(0, 0, 255);
                life1 = life1 - 5;
                sync.filled_rectangle(0, 105, life, 108, SKY_COLOR);
                sync.filled_rectangle(0, 105, life1, 108, RED);
                t1.turnback();
                t2.turnback();
                sync.update();  // Is this necessary?
                winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
            }else if(sync.pixel_eq(intersection_code, t2.tank_color)) { // If you shot the other guy, you won!
                pc.printf("c2!\n");
                //RGB_LED(0, 0, 255);
                life2 = life2 - 5;
                t1.turnback();
                t2.turnback();
                sync.filled_rectangle(128-life, 105, 128, 108, SKY_COLOR);
                sync.filled_rectangle(128-life2, 105, 128, 108, RED);
                sync.update();
                winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
            } else if (intersection_code == BULLET_NO_COLLISION){
               pc.printf("c3!\n");
               sync.update();
            } else {
                pc.printf("c4!\n");
                //RGB_LED(0, 0, 255);
                whose_turn = PLAYER2;
                turn++;
                t1.turnback();
                t2.turnback();
                sync.locate(0,15);;
                char title[10];
                sprintf(title, "Turn %d", turn);
                sync.puts(title, sizeof(title));
            }
            
        } else if(whose_turn == PLAYER2) {
            
                if(sync.play_mode == MULTI_PLAYER ){
                    if(p2_buttons[R_BUTTON]) { 
                        t2.invisible(); 
                    }
                                // Accelerometer example
                    if(ax2 > ACC_THRESHOLD) { 
                        // Move the tank to the right if the accelerometer is tipped far enough to the right.
                         t2.reposition(+1, 0, 0);          
                    } else if(ax2 <  -ACC_THRESHOLD){
                        t2.reposition(-1, 0, 0);  
                    }
                    
                    if(ay2 >  ACC_THRESHOLD) { 
                        // Move the tank to the right if the accelerometer is tipped far enough to the right.
                        t2.reposition(0, 0, -PI/10);          
                    } else if(ay2 <  -ACC_THRESHOLD){
                        t2.reposition(0, 0, PI/10);  
                    }
                    // Button example
                    if(p2_buttons[D_BUTTON]) { 
                        b2.shoot(); 
                    }
                    
                    float dt = frame_timer.read();
                    int intersection_code = b2.time_step(dt);
                    if(intersection_code == BULLET_OFF_SCREEN) { 
                        pc.printf("Now it's P1's turn!\n");
                        //RGB_LED(0, 0, 255);
                        whose_turn = PLAYER1;
                        turn++;
                        t1.turnback();
                        t2.turnback();
                        sync.locate(0,15);;
                        char title[10];
                        sprintf(title, "Turn %d", turn);
                        sync.puts(title, sizeof(title));
                    } else if(sync.pixel_eq(intersection_code, t2.tank_color)) { // If you shot yourself, you lost.
                        pc.printf("s1!\n");
                        //RGB_LED(0, 0, 255);
                        life2 = life2 - 5;
                        t1.turnback();
                        t2.turnback();
                        sync.filled_rectangle(128-life, 105, 128, 108, SKY_COLOR);
                        sync.filled_rectangle(128-life2, 105, 128, 108, RED);
                        sync.update();  // Is this necessary?
                        winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
                    }else if(sync.pixel_eq(intersection_code, t1.tank_color)) { // If you shot the other guy, you won!
                        pc.printf("s2!\n");
                        //RGB_LED(0, 0, 255);
                        life1 = life1 - 5;
                        t1.turnback();
                        t2.turnback();
                        sync.filled_rectangle(0, 105, life, 108, SKY_COLOR);
                        sync.filled_rectangle(0, 105, life1, 108, RED);
                        sync.update();
                        winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
                    } else if (intersection_code == BULLET_NO_COLLISION){
                       pc.printf("s3!\n");
                       sync.update();
                    } else {
                        pc.printf("s4!\n");
                        //RGB_LED(0, 0, 255);
                        whose_turn = PLAYER1;
                        turn++;
                        t1.turnback();
                        t2.turnback();
                        sync.locate(0,15);;
                        char title[10];
                        sprintf(title, "Turn %d", turn);
                        sync.puts(title, sizeof(title));
                    }
                    wait(0.1); 
                
                } else{
                    if(p1_buttons[R_BUTTON]) { 
                        t2.invisible(); 
                    }
                                // Accelerometer example
                    if(ax1 > ACC_THRESHOLD) { 
                        // Move the tank to the right if the accelerometer is tipped far enough to the right.
                         t2.reposition(+1, 0, 0);          
                    } else if(ax1 <  -ACC_THRESHOLD){
                        t2.reposition(-1, 0, 0);  
                    }
                    
                    if(ay1 >  ACC_THRESHOLD) { 
                        // Move the tank to the right if the accelerometer is tipped far enough to the right.
                        t2.reposition(0, 0, -PI/10);          
                    } else if(ay1 <  -ACC_THRESHOLD){
                        t2.reposition(0, 0, PI/10);  
                    }
                    // Button example
                    if(p1_buttons[D_BUTTON]) { 
                        b2.shoot(); 
                    }
                    
                    float dt = frame_timer.read();
                    int intersection_code = b2.time_step(dt); 
                    if(intersection_code == BULLET_OFF_SCREEN) { 
                        pc.printf("Now it's P1's turn!\n");
                        //RGB_LED(0, 0, 255);
                        whose_turn = PLAYER1;
                        turn++;
                        t1.turnback();
                        t2.turnback();
                        sync.locate(0,15);
                        char title[10];
                        sprintf(title, "Turn %d", turn);
                        sync.puts(title, sizeof(title));
                        
                    } else if(sync.pixel_eq(intersection_code, t2.tank_color)) { // If you shot yourself, you lost.
                        pc.printf("s1!\n");
                        //RGB_LED(255, 0, 0);
                        life2 = life2 - 5;
                        t1.turnback();
                        t2.turnback();
                        sync.filled_rectangle(128-life, 105, 128, 108, SKY_COLOR);
                        sync.filled_rectangle(128-life2, 105, 128, 108, RED);
                        sync.update();
                        
                        winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
                    }else if(sync.pixel_eq(intersection_code, t1.tank_color)) { // If you shot the other guy, you won!
                        pc.printf("s2!\n");
                         //RGB_LED(0, 0, 255);
                        life1 = life1 - 5;
                        t1.turnback();
                        t2.turnback();
                        sync.filled_rectangle(0, 105, life, 108, SKY_COLOR);
                        sync.filled_rectangle(0, 105, life1, 108, RED);
                        sync.update();
                        winner = winner_dec(life1,life2,&won_round1,&won_round2,life,&t1,&t2);
                        pc.printf("player 2 wins\n");
                    } else if (intersection_code == BULLET_NO_COLLISION){
                       pc.printf("s3!\n");
                       sync.update();
                    } else {
                        pc.printf("s4!\n");
                        whose_turn = PLAYER1;
                        //RGB_LED(0, 0, 255);
                        turn++;
                        t1.turnback();
                        t2.turnback();
                        sync.locate(0,15);
                        char title[10];
                        sprintf(title, "Turn %d", turn);
                        sync.puts(title, sizeof(title));
                    }
                
                
                }
            // I gave you a lot of the logic for Player1. It's up to you to figure out Player2!
            // If you are in SINGLE_PLAYER mode, you should use the p1 inputs to control p2.
            // In MULTI_PLAYER mode, you should use the p2 inputs to control p2.
            //
            // Hint: 
            //         sync.play_mode will tell you if you are in MULTI_PLAYER or SINGLE_PLAYER mode.
            //         

        }

        frame_timer.reset();
        sync.update();     
    } 
    pc.printf("here");
    game_over();
    
}