package edu.fiu.models;

import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Used to identify users and transactions made against the API
 *
 * @author Dan Herrera
 */
public class Session {

  protected Integer id;             // Session ID in data store
  protected String token;           // Identifying token (GUID? seems to be easiest solution)
  protected List<Integer> userIds; // List of users for session
  protected boolean active;         // Tracks whether session is active
  protected String dateTime;          // Tracks the last time a session was created or checked

  public static class Mapper implements RowMapper<Session> {
    @Override public Session map(final ResultSet rs, final StatementContext ctx) throws SQLException {

      //Convert string ids into int list
      String list = rs.getString("userIds");
      String[] ids = list.split(",");
      List<Integer> userIds = new ArrayList<Integer>();
      for (String id : ids)
      {
        Integer i = Integer.parseInt(id);
        userIds.add(i);
      }

      return new Session(rs.getInt("id"), rs.getString("token"), userIds, rs.getBoolean("active"), rs.getString("dateTime"));
    }
  }

  public Session(Integer id, String token, List<Integer> userIds, boolean active, String dateTime) {
    this.id = id;
    this.userIds = userIds;
    this.token = token;
    this.active = active;
    this.dateTime = dateTime; 
  }

  //Getters and Setters
  public Integer getId()
  {
    return id;
  }

  public void setId(Integer id)
  {
    this.id = id;
  }

  public List<Integer> getUserIds()
  {
    return this.userIds;
  }

  public void setUserIds(List<Integer> userIds)
  {
    this.userIds = userIds;
  }

  public String getToken(){
    return this.token;
  }

  public void setToken(String token) {
    this.token = token; 
  }

  public boolean isActive()
  {
    return active;
  }

  public void setActive(boolean active)
  {
    this.active = active;
  }

  public String getDateTime()
  {
    return this.dateTime;
  }

  public void setDatetime(String dateTime)
  {
    this.dateTime = dateTime;
  }

  public String toString(){
    return String.format("Session<%d, %s, %s, %s>", id, userIds, token, active ? "active":"inactive");
  }

}
