//Rev 2
#include <SD.h>

const int Charge = 825;      //The over/under telling us if current is being drawn

const int chipSelect = 10;
const int Alarm = 7;
const int GraceTime = 10000;  //Grace period to insert the phone, in milliseconds.

unsigned long pTimer = 0;
unsigned long deltaTime = 0;
int Status = 0;

String dataString = "";

//States:
//0 = Car turned on, grace period
//1 = Phone detected in docl
//2 = Phone NOT detected in dock

void setup()
{
  Serial.begin(9600);
  
  pinMode(Alarm, 1);
  analogReference(DEFAULT);

  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("Done.");
}

void loop() {                        //When the car / power starts, this loop executes.

pTimer += 1;                      //Increment timer
delay(1);                         //Do delay so timer is approximately in Milliseconds
  
if (analogRead(A0) > Charge) {      //Current being drawn?

    dataString = "";              //Clear string    
    digitalWrite(Alarm, 0);        //No matter what, this turns OFF the alarm.

	if (Status == 0) {              //Phone inserted for first time / car start?    
    
    Status = 1;   
    File dataFile = SD.open("good.txt", FILE_WRITE);    //Open "Good" file and set to WRITE so we can append a line      
    if (dataFile) {                                     //Make sure it opened.          
      if (pTimer < 100) {                                 //Phone plugged in as car started?
        dataFile.println("Car started with phone already in dock.");
        dataFile.close();       
      }
      else {                                            //Phone plugged in before grace period?
        dataFile.print("Car started, phone inserted after ");
        dataString += String(pTimer / 1000);
        dataFile.print(dataString);
        dataFile.println(" seconds.");
        dataFile.close();  
      }     
    }          
  }

  if (Status == 2) {              //Phone WAS previously in the dock, they removed it then put it back in. 
      
      Status = 1;  
      File dataFile = SD.open("bad.txt", FILE_WRITE);    
        if (dataFile) {         
          dataFile.print("Phone re-inserted after ");
          dataString += String((pTimer - deltaTime) / 1000);  //Calculate time between.
          dataFile.print(dataString);
          dataFile.println(" seconds.");
          dataFile.close();   
        }      
	}       

} //if (analogRead(A0) > Charge)
  
 
if ((analogRead(A0) < Charge) and (pTimer >= GraceTime)) {    //Phone not drawing current after grace period?

    dataString = "";                                     //Clear string    
    digitalWrite(Alarm, 1);                                  //No matter what else, sound the alarm

    delay(500);                           //Prevent false logs because of the car being shut off.
  
    if (Status == 1) {                    //Was phone already in the dock once? (did they pull it out again?)

        File dataFile = SD.open("bad.txt", FILE_WRITE);      //Open "Good" file and set to WRITE so we can append a line      
        if (dataFile) {                                      //Make sure it opened.          
            dataFile.print("Phone REMOVED from dock while car running! ");
            if (pTimer < 60000) {            
              dataString += String(pTimer / 1000);      	//In seconds?
              dataFile.print(dataString);
              dataFile.println(" seconds after car started");
            }
            else {
              dataString += String((pTimer / 1000) / 60);      //Or minutes?            
              dataFile.print(dataString);
              dataFile.println(" minutes after car started");
            }           
            dataFile.close();   
        }      
      
		deltaTime = pTimer;                                       //Get current time, so when they hopefully put the phone back in, we can log how long it took them.
		Status = 2;        
    }
    
    if (Status == 0) {

        File dataFile = SD.open("bad.txt", FILE_WRITE);      //Open "Good" file and set to WRITE so we can append a line      
			if (dataFile) {                                      //Make sure it opened.          
				dataFile.println("Car started, phone NOT INSERTED within grace period.");
				dataFile.close();   
			}      
       deltaTime = pTimer;
       Status = 2;       
      
    }


}




}
