package facebookpagestats.model;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 *
 * @author trust56
 */
public class FacebookPageStats extends ArrayList<FacebookPageStat> {
// http://graph.facebook.com/40796308305

  public boolean addNewPage(String pageTitle) throws MalformedURLException,
          IOException {
    FacebookPageStat fps = new FacebookPageStat();
    loadPageStat(pageTitle, fps);
    add(fps);
    return true;
  }

  private void loadPageStat(String pageTitle, FacebookPageStat fps) throws
          IOException, NumberFormatException, MalformedURLException {
    URL url = new URL("http://graph.facebook.com/" + pageTitle
            + "?fields=id,name,picture,about,website,likes");
    InputStream is = url.openConnection().getInputStream();
    Scanner sc = new Scanner(is);
    sc.useDelimiter("\\{|\\}");
    while (sc.hasNext()) {
      String dataField = sc.next();
      Scanner scI = new Scanner(dataField);
      scI.useDelimiter(",\"");
      while (scI.hasNext()) {
        String data = scI.next();
        //System.out.println(data);
        if (data.startsWith("\"id\":")) {
          fps.setId(Long.parseLong(data.split("\"")[3]));
        } else if (data.startsWith("name\":")) {
          fps.setName(data.split("\"")[2]);
        } else if (data.startsWith("about\":")) {
          fps.setAbout(data.split("\"")[2]);
        } else if (data.startsWith("website\":")) {
          fps.setWebsite(new URL(data.split("\"")[2].replace("\\", "")));
        } else if (data.startsWith("likes\":")) {
          fps.setLikes(Long.parseLong(data.split(":")[1]));
        } else if (data.startsWith("\"url\":")) {
          fps.setPicture(new URL(data.split("\"")[3].replace("\\", "")));
        }
      }
    }
    is.close();
  }

  public void startObserve() {
    new Timer().schedule(new TimerTask() {
      public void run() {
        for (FacebookPageStat facebookPageStat : FacebookPageStats.this) {
          try {
            loadPageStat(facebookPageStat.getId() + "", facebookPageStat);
            for (FacebookPageStatRefreshListener facebookPageStatRefreshListener : listeners) {
              facebookPageStatRefreshListener.facebookPageStatRefreshed(
                      new FacebookPageStatRefreshEvent(this, indexOf(facebookPageStat)));
            }
          } catch (NumberFormatException ex) {
            System.err.println(ex.getMessage());
          } catch (MalformedURLException ex) {
            System.err.println(ex.getMessage());
          } catch (IOException ex) {
            System.err.println(ex.getMessage());
          }
        }
      }
    }, 5_000, 5_000);
  }
  private List<FacebookPageStatRefreshListener> listeners = new ArrayList<>();

  public void addFacebookPageStatRefreshListener(FacebookPageStatRefreshListener listener) {
    listeners.add(listener);
  }

  public void removeFacebookPageStatRefreshListener(FacebookPageStatRefreshListener listener) {
    listeners.remove(listener);
  }

  public void savePageList(String fileName) throws FileNotFoundException, IOException {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(fileName));
    dos.writeInt(size());
    for (FacebookPageStat facebookPageStat : this) {
      dos.writeLong(facebookPageStat.getId());
    }
    dos.flush();
    dos.close();
  }

  public void loadPageList(String fileName) throws FileNotFoundException, IOException {
    DataInputStream dis = new DataInputStream(new FileInputStream(fileName));
    int n = dis.readInt();
    clear();
    for (int i = 0; i < n; i++) {
      addNewPage(dis.readLong() + "");
    }
  }
}
