
#include <SPI.h>

#include <stdint.h>
#include "Adafruit_GFX.h"
#include "Adafruit_HX8357.h"
#include "TouchScreen.h"
#include "/usr/share/arduino/libraries/SPI/SPI.h"

#define NUM_TOOLS 16
#define MAX_USERS 16

//Touchscreen #defines
#define USER_BTN_X 60
#define LOCK_BTN_X 290
#define BTN_WIDTH 120

#define TFT_CS 12
#define TFT_DC 11
#define TFT_RST -1

// These are the four touchscreen analog pins
#define YP A3  // must be an analog pin, use "An" notation!
#define XM A1  // must be an analog pin, use "An" notation!
#define YM A2   // can be a digital pin
#define XP A0   // can be a digital pin

//Select Lines
#define MUX_S0 20
#define MUX_S1 19
#define MUX_S2 16
#define MUX_S3 17
#define MUX_OUT 18

//Servo Constraints
#define LOCK_PULSE 760 //SET ACCORDINGLY
#define UNLOCK_PULSE 870 //SET ACCORDINGLY

int count = 0;


//Touch Screen
// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
Adafruit_HX8357 tft = Adafruit_HX8357(TFT_CS, TFT_DC, TFT_RST);
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
int x = 0;
int y = 0;
int lock_button = 0;
int add_user_button = 0;
int btn_code = 0;

//Servo
int servoPin = 4;     // Control pin for servo motor
int lastPulse = 0;    // the time in milliseconds of the last pulse
int refreshTime = 20; // the time needed in between pulses

int locked = 1; //CHANGE BACK TO 1
int lock_timer = 0;

int valid_pin = 0;
int id_pin = 1;

//inventory
boolean tools[NUM_TOOLS];
int user[NUM_TOOLS] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //{0,1,0,1,0,1,-1,0,1,0,1,0,1,-1,-1,-1};
int all_tools;
uint16_t color;
uint16_t status_color;
char status_msg[19];

//Drawer Switches
#define TOP 5
#define BOT 6

void setup() {
  
  //Set servo pin as output
  pinMode(servoPin, OUTPUT);  // Set servo pin as an output pin
  
  //Set select as output
  pinMode(MUX_S0,OUTPUT);
  pinMode(MUX_S1,OUTPUT);
  pinMode(MUX_S2,OUTPUT);
  pinMode(MUX_S3,OUTPUT);
  pinMode(MUX_OUT,INPUT);
  
  tft.begin(HX8357D);

  tft.setRotation(3);
  tft.fillScreen(HX8357_WHITE);
  
  tft.fillRect(USER_BTN_X, 100, 120, 40, HX8357_WHITE); //clear
  tft.fillRect(LOCK_BTN_X, 100, 140, 40, HX8357_WHITE); //clear
  
  tft.drawRoundRect(USER_BTN_X, 100, 120, 40, 6, HX8357_BLACK);
  tft.drawRoundRect(LOCK_BTN_X, 100, 140, 40, 6, HX8357_BLACK);
  
  tft.setTextColor(HX8357_BLACK);
  tft.setTextSize(2);
  tft.setCursor(tft.width()/4 - 50, 115);
  tft.print("Add User");
  tft.setCursor(3*tft.width()/4 - 60, 115);
  tft.print("Lock Chest");
  
  //Get Tool Data
  getTools();
  drawTools();
  delay(500);
}


void loop(void) {
  /*btn_code = readTouch(); //sets button pressed variable to 1
   
  if(btn_code == 1) //Add user button
  {
    tft.fillRect(USER_BTN_X, 100, 120, 40, HX8357_GREEN); //clear
  
    tft.drawRoundRect(USER_BTN_X, 100, 120, 40, 6, HX8357_BLACK);
    
    tft.setTextColor(HX8357_BLACK);
    tft.setTextSize(2);
    tft.setCursor(tft.width()/4 - 50, 115);
    tft.print("Add User");
  }
  else  if(btn_code == 2) //lock button
  {
    tft.fillRect(USER_BTN_X, 100, 120, 40, HX8357_RED); //clear
  
    tft.drawRoundRect(USER_BTN_X, 100, 120, 40, 6, HX8357_BLACK);
    
    tft.setTextColor(HX8357_BLACK);
    tft.setTextSize(2);
    tft.setCursor(tft.width()/4 - 50, 115);
    tft.print("Add User");
  }*/
  delay(1000);
  if(locked)
  {
    //Check pins from UNO
    while(!digitalRead(valid_pin));
    unlockChest();
  }
  
  //Check locked timer flag
  if(!digitalRead(TOP) & !digitalRead(BOT))
  {
    lock_timer++;
    if(lock_timer  == 10)
    {
      lockChest(); //dont lock while open, check drawer contacts in function
      getTools();
      drawTools();
    }
    else
    {
      //Get touch coordinates, check for buttons
      btn_code = readTouch(); //sets button pressed variable to 1
     
      if(btn_code == 1) //Add user button
      {
        //add_credentials();
        //??
      }
      else if(btn_code == 2) //lock button
      {
        lockChest();
        getTools();
        drawTools();
      }
    }
  }
  else
  {
    lock_timer = 0;
  }
    
 
//  if(!digitalRead(TOP) & !digitalRead(BOT) & lock_timer >= 10000)// & locked) //drawer closed in state machine
//  {
//    getTools();
//    drawTools();
//  }
  
  //TSPoint p = ts.getPoint();
  //tft.setCursor(x,count*20);
  //tft.print("X:");
  //tft.print(p.x);
  //tft.setCursor(x,(count*20)+10);
  //tft.print("Y:");
  //tft.print(p.x);
  //tft.setCursor(x,count*20);
  //y = ts.readTouchX();
  //tft.print("X:");
  //tft.print(y);
  //tft.setCursor(x,(count*20)+10);
  //y = ts.readTouchY();
  //tft.print("Y:");
  //tft.print(y);
  //y = ts.readTouchX();
  //tft.fillRect(x,count*20,30,10,HX8357_RED);
  //tft.print("P:");
  //tft.print(y);
  //count++;
  //if(count == 15){
  //  x+=40;
  //  count = 0;
  //}
  //if(x == 480)
  //{
  //  x = 0;
  //}
}

void getTools()
{
  delay(1000);
  int val;
  //check drawer switches
 for(int i=0; i<16; i++)
 {
  setSelect(i);
  val = (digitalRead(MUX_OUT) == 0);
  if(tools[i] & (val == 0))
  {
    user[i] = digitalRead(id_pin);
  }
  tools[i] = (digitalRead(MUX_OUT) == 0);
 }
}

void drawTools()
{
  tft.fillRect(0, 160, tft.width(), tft.height()/2, HX8357_WHITE); //clear
  
  tft.drawRoundRect(10, 160, tft.width()/2 - 20, tft.height()/2 - 2, 6, HX8357_BLACK);
  tft.drawRoundRect(tft.width()/2 + 10, 160, tft.width()/2 - 20, tft.height()/2 - 2, 6, HX8357_BLACK);
  
  //Headers
  tft.setTextSize(2);
  tft.setCursor(60, 175);
  tft.print("TOP DRAWER");
  
  tft.setCursor(tft.width()/2 + 60, 175);
  tft.print("BOTTOM DRAWER");
  
  all_tools = 1;
 //Tool Entries 1
  tft.setTextSize(2);
  for(int i = 0; i < 8; i ++)
  {
    if(tools[i])
    {
      color = HX8357_GREEN;
      tft.setCursor(35, 195 + 15*i);
      tft.print("Tool " + String(i+1));
    }
    else
    {
      color = HX8357_RED;
      all_tools = 0;
      //get user
      tft.setCursor(35, 195 + 15*i);
      if(user[i] == 0)
      {
        tft.print("Tool " + String(i+1) + " - 669");
      }
      else if(user[i] == 1)
      {
        tft.print("Tool " + String(i+1) + " - 657");
      }
      else //-1
      {
         tft.print("Tool " + String(i+1) + " - NONE");
      }
      
    }
    tft.fillRoundRect(20,195+15*i,10,10,3,color);
  }
  
  //Tool Entries 2
  for(int i = 0; i < 8; i ++)
  {
    if(tools[i+8])
    {
      color = HX8357_GREEN;
      tft.setCursor(tft.width()/2 + 35, 195 + 15*i);
      tft.print("Tool " + String(i+9));
    }
    else
    {
      color = HX8357_RED;
      all_tools = 0;
      tft.setCursor(tft.width()/2 + 35, 195 + 15*i);
      if(user[i+8] == 0)
      {
        tft.print("Tool " + String(i+9) + " - 669");
      }
      else if(user[i+8] == 1)
      {
        tft.print("Tool " + String(i+9) + " - 657");
      }
      else //-1
      {
         tft.print("Tool " + String(i+9) + " - NONE");
      }
    }
    tft.fillRoundRect(tft.width()/2 + 20,195+15*i,10,10,3,color);
  }

  if(all_tools)
  {
    status_color = HX8357_GREEN;
    tft.fillRect(90, 40, 400, 25, HX8357_WHITE); //clear text
    tft.setCursor(90, 40);
    tft.setTextSize(3);
    tft.print("All tools are in!");
  }
  else
  {
    status_color = HX8357_RED;
    tft.fillRect(90, 40, 400, 25, HX8357_WHITE); //clear text
    tft.setCursor(90, 40);
    tft.setTextSize(3);
    tft.print("Missing some tools!");
  }
  tft.fillRect(20,20,60,60,HX8357_WHITE); //clear button
  tft.fillRoundRect(20,20,60,60,10,status_color);
  
}

void setSelect(int num)
{
  //Use port manipulation to set all at once?
  digitalWrite(MUX_S0,num%2); //MUX_S0 set 1,3,5,7,9,11,13,15
  digitalWrite(MUX_S1,(num>>1)%2); //MUX_S1  set 2,3,6,7,
  digitalWrite(MUX_S2,(num>>2)%2); //MUX_S2
  digitalWrite(MUX_S3,(num>>3)%2); //MUX_S3  
  delay(15);
}

void lockChest() //dont lock while open, check drawer contacts in function
{
  if(locked == 1)
  {
    //error, set some error pin high?
     return;
  }
  for(int i=0;i<200;i++)
  {
    digitalWrite(servoPin, HIGH);   // Turn the motor on
    delayMicroseconds(LOCK_PULSE);       // Length of the pulse sets the motor position
    digitalWrite(servoPin, LOW);    // Turn the motor off
    delayMicroseconds(20000-LOCK_PULSE); // Wait
  }
  locked = 1;
}

void unlockChest() //dont unlock while open, check drawer contacts in function??
{
  if(locked == 0)
  {
    //error, set some error pin high?
     return;
  }
  for(int i=0;i<200;i++)
  {
    digitalWrite(servoPin, HIGH);   // Turn the motor on
    delayMicroseconds(UNLOCK_PULSE);       // Length of the pulse sets the motor position
    digitalWrite(servoPin, LOW);    // Turn the motor off
    delayMicroseconds(20000-UNLOCK_PULSE); // Wait
  }
  locked = 0;
}
/*
void check_credentials()
{
 //local vars
 int cred_valid = 0;
  
  
 //Print prompt to swipe card
 
 //Clear card reader interrupt flag
 card_read = 0;
 
 //Set variable and fill credentials in interrupt

 //Need to wait for card reader to return values 
 while(1)
 {
   if(card_read)
   {
     delay(500);
     //Check array for proper credentials
     for(unsigned int i=0; i<strlen(card_val); i++)
     {
       cred_valid = 1;
       for(unsigned int j=0; j<strlen(credentials[j]); j++)
       {
         if(card_val[i] != credentials[j][i])
         {
           cred_valid = 0;
           //break;??
         }
       }
       
       if(cred_valid == 1)
       {
         break;
       }
       
     }
     if(cred_valid == 1)
     {
       unlockChest();
       break;
     }
     card_read = 0;
   }
 }
 return;
}

void add_credentials()
{
 //Print prompt to swipe card
 
 //Clear card reader interrupt flag
 card_read = 0;
 
 //Set variable and fill credentials in interrupt

 //Need to wait for card reader to return values
 while(1)
 {
   if(card_read)
   {
     delay(500);
     //Check array for proper credentials
     for(unsigned int i=0; i<strlen(card_val); i++)
     {
       credentials[num_users][i] = card_val[i];       
     }
     num_users++;
     card_read = 0;
     break;
   }
 }
 return;
}
*/
int readTouch()
{
 return 0;
 
 TSPoint p = ts.getPoint();
 if((p.x > USER_BTN_X) & (p.x < USER_BTN_X + BTN_WIDTH))
 {
   return 1; //user button
 }
 if((p.x > LOCK_BTN_X) & (p.x < LOCK_BTN_X + BTN_WIDTH))
 {
   return 2; //lock button
 }
 return 0;
}

