/*## (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 javax.tv.service.*;
import javax.tv.locator.*;

public class ECMForwarder extends ECMHandler {
 String name;
 StreamOutput out;
 String srvname;
 String srvlocator;

 public ECMForwarder() {
  super("ECM Forwarder");

  try {
   SrvConnection conn=SrvConnection.get(Proto.CLT_BOX);
   out=conn.output();
   out.set_data_type(Proto.CMD_ANNOUNCEMENT);
  } catch(Throwable t) {
   ApiMonitor.log_stacktrace(t);
  }
 }

 public void start(int channel) {
  try {
   Service srv=SrvUtils.srv_by_channel(channel);
   srvname=srv.getName();
   srvlocator=srv.getLocator().toString();

   out.write_byte(Proto.AN_ECM_FORWARDER_STARTED);
   out.write_string(srvname);
   out.write_string(srvlocator);
   out.flush();
  } catch(Throwable t) {
   ApiMonitor.log_stacktrace(t);
  }
 }

 public void stop(int channel) {
  try {
   out.write_byte(Proto.AN_ECM_FORWARDER_STOPPED);
   out.write_string(srvname);
   out.write_string(srvlocator);
   out.flush();
  } catch(Throwable t) {
   ApiMonitor.log_stacktrace(t);
  }
 }

 public void handle_ecm(int channel,int cur_idx,int cur_cw[],int next_idx,int next_cw[]) {
  try {
   ApiMonitor.log("ECMForwarder handle ecm");
   ApiMonitor.log(" cur_cw[0]  "+Utils.hex_value(cur_cw[0],8));
   ApiMonitor.log(" cur_cw[1]  "+Utils.hex_value(cur_cw[1],8));
   ApiMonitor.log(" next_cw[0] "+Utils.hex_value(next_cw[0],8));
   ApiMonitor.log(" next_cw[1] "+Utils.hex_value(next_cw[1],8));

   out.write_byte(Proto.AN_ECM_DATA);
   out.write_string(srvlocator);
   out.write_int(ECMServer.ecm_stamp());
   out.write_int(cur_cw[0]);
   out.write_int(cur_cw[1]);
   out.write_int(next_cw[0]);
   out.write_int(next_cw[1]);
   out.flush();
  } catch(Throwable t) {
   ApiMonitor.log_stacktrace(t);
  }
 }

}
