/**
 * djData follow me on Facebook!
 * ArtHackDay - Sight and Sound edition - PER CAPITA
 * a project by userZero & linse
 * 01/10/16
 */
import oscP5.*;
import netP5.*;

OscP5 oscP5;
NetAddress myRemoteLocation;

String access_token ="EAACEdEose0cBAOZA2CnpqAZAZBI67DeSpKycTcFRIuhtr1LLOHzsoc41ZBn95rdcdZCCCsBGlWmbHZC0qER7qvkTkMlAeM2NNjhzhACwmriLkhE8EqSQ5U9AGq58eDomeQ0eHZCZBWtEzmiBnFE2xEugrtFPZA0bXJeRpIfhXaM0OWgZDZD";
int lastSecond = 0;
int likes = 0;
ArrayList<String> messageList;

ArrayList<String> musicGenres;

void setup() {
  oscP5 = new OscP5(this,4343);
  // connect to pd Patch
  myRemoteLocation = new NetAddress("127.0.0.1",4242);
  messageList = new ArrayList();
  loadMusic("/home/mxd/arthackday/sounds");
}

void draw() {
  if(second()%3 == 1 && lastSecond != second()){
    pollFeed();
    pollLikes();
  }
}

void loadMusic(String _dir){
  String[] _files = split(getFileNames(_dir), ' ');
  musicGenres = new ArrayList();
  String[] _tmp;
  for(String _s : _files){
    _tmp = split(_s, '.');
    if(_tmp.length > 1){
      if(_tmp[1].equals("wav")) musicGenres.add(_tmp[0]);
    }
  }
  println("////////////////////// MUSIC /////////////////////////");
  println(musicGenres);
  println("//////////////////////////////////////////////////////");

}


public String getFileNames(String _dir){
  File userData = new File(_dir);
  File[] listOfFiles = userData.listFiles();
  String _out = "";
  for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
      _out +=  listOfFiles[i].getName()+" ";
    } else if (listOfFiles[i].isDirectory()) {
    }
  }
  return _out;
}

public void checkForMusic(String _message){
  String _keyWords[] = _message.replaceAll("[^a-zA-Z0-9_]", "").toLowerCase().split("_");//.replaceAll(".","_")
  println("///////////////////////////////////////////////");

  for(String _word : _keyWords){
    println(_word);
    for(String _genre : musicGenres){
      if(_word.equals(_genre)) play(_word);
    }
  }
  println("///////////////////////////////////////////////");

}



void pollLikes(){
  String response[] = loadStrings("https://graph.facebook.com/?fields=likes&id=http://www.facebook.com/djdaataa&access_token="+access_token);
  lastSecond = second();
  if(response == null){
    println("request FAIL");
    return;
  }
  String str = "";
  for(int i = 0; i < response.length;i++)
  str+=response[i];
  JSONObject json = JSONObject.parse(str);
  like(json.getInt("likes"));
}


void pollFeed(){

  String response[] = loadStrings(" https://graph.facebook.com/1272223639476617/feed?access_token="+access_token);
  lastSecond = second();

  if(response == null){
    println("request FAIL");
    return;
  }
  println("GOT response");

  String str = "";
  for(int i = 0; i < response.length;i++)
  str+=response[i];
  JSONObject json = JSONObject.parse(str);
  JSONArray data = json.getJSONArray("data");

  ArrayList<String> _polledMessages = new ArrayList();

  for(int i = 0; i < data.size(); i++){
    if(!data.getJSONObject(i).isNull("message")){
      JSONObject from = data.getJSONObject(i).getJSONObject("from");
      String _mess = from.getString("name")+" says "+data.getJSONObject(i).getString("message");
      _polledMessages.add(_mess.replaceAll(" ", "_"));
    }
  }
  receiveMessages(_polledMessages);
}

void receiveMessages(ArrayList<String> _polledMessages){
  int _newCount = _polledMessages.size() - messageList.size();
  if(_polledMessages.size() > 0 && messageList.size() > 0)
  if(!_polledMessages.get(0).equals(messageList.get(0))) _newCount = 1;
  if(_newCount != 0){
    messageList = _polledMessages;
    String _mess = "";
    for(int i = 0; i < _newCount; i++){
      _mess += messageList.get(i)+" ";
    }
    post(_mess);
  }
}

public void play(String _genre){
  print("PLAYING ");
  println(_genre);
  OscMessage mess = new OscMessage("/datadj/play");
  mess.add(_genre+".wav");
  oscP5.send(mess, myRemoteLocation);
}

void post(String _mess){
  println("SENDING : "+ _mess);
  OscMessage mess = new OscMessage("/datadj/posts");
  mess.add(_mess);
  oscP5.send(mess, myRemoteLocation);
  checkForMusic(_mess);
}

void like(int _cnt){
  if(_cnt != likes) {
    likes = _cnt;
    println("LIKES : "+_cnt);
    OscMessage mess = new OscMessage("/datadj/likes");
    mess.add(_cnt);
    oscP5.send(mess, myRemoteLocation);
  }
}

// set new token LIVE
void oscEvent(OscMessage theOscMessage) {
  if(theOscMessage.checkAddrPattern("/token")==true) {
      access_token = theOscMessage.get(0).stringValue();
      println("NEW TOKEN : "+access_token);
  }
}