/*## (c) SECURITY EXPLORATIONS    2018 poland                                #*/
/*##     http://www.security-explorations.com                                #*/

/* THIS SOFTWARE IS PROTECTED BY DOMESTIC AND INTERNATIONAL COPYRIGHT LAWS    */
/* UNAUTHORISED COPYING OF THIS SOFTWARE IN EITHER SOURCE OR BINARY FORM IS   */
/* EXPRESSLY FORBIDDEN. ANY USE, INCLUDING THE REPRODUCTION, MODIFICATION,    */
/* DISTRIBUTION, TRANSMISSION, RE-PUBLICATION, STORAGE OR DISPLAY OF ANY      */
/* PART OF THE SOFTWARE, FOR COMMERCIAL OR ANY OTHER PURPOSES REQUIRES A      */
/* VALID LICENSE FROM THE COPYRIGHT HOLDER.                                   */

/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS    */
/* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,*/
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    */
/* SECURITY EXPLORATIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF  */
/* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE     */
/* SOFTWARE.                                                                  */

import java.lang.*;
import java.util.*;

public class ECMProvider implements DaemonThread.Code {
 protected boolean running;
 Vector handlers;
 int channel;

 public ECMProvider(int channel) {
  handlers=new Vector();
  running=false;
  this.channel=channel;
 }
 
 public void run(Object args[]) {
 }

 public void start() {
  try {
   start_handlers();
   DaemonThread.start(this,null);    
   running=true;
  } catch(Throwable t) {}
 }

 public void stop() {
  running=false;
  stop_handlers();
 }

 public boolean status() {
  return running;
 }

 private boolean registered(ECMHandler handle) {
  synchronized(handlers) {
   for(int i=0;i<handlers.size();i++) {
    ECMHandler h=(ECMHandler)handlers.elementAt(i);
    String name=h.name();

    if (handle.name().equals(name)) return true;
   }
  }

  return false;
 }

 public boolean register_handler(ECMHandler handle) {
  if (registered(handle)) return false;

  synchronized(handlers) {
   handlers.addElement(handle);
  }

  return true;
 }

 public void start_handlers() {
  synchronized(handlers) {
   for(int i=0;i<handlers.size();i++) {
    ECMHandler handle=(ECMHandler)handlers.elementAt(i);
    handle.start(channel);
   }
  }
 }

 public void stop_handlers() {
  synchronized(handlers) {
   for(int i=0;i<handlers.size();i++) {
    ECMHandler handle=(ECMHandler)handlers.elementAt(i);
    handle.stop(channel);
   }
  }
 }

 public void process_handlers(int cur_idx,int[] cur_cw,int next_idx,int[] next_cw) {
  synchronized(handlers) {
   for(int i=0;i<handlers.size();i++) {
    ECMHandler handle=(ECMHandler)handlers.elementAt(i);
    handle.handle_ecm(channel,cur_idx,cur_cw,next_idx,next_cw);
   }
  }
 }
}
