/*
NAME
  session.go

DESCRIPTION
  See Readme.md

AUTHORS
  Saxon Nelson-Milton <saxon@ausocean.org>
  Dan Kortschak <dan@ausocean.org>

LICENSE
  session.go is Copyright (C) 2017 the Australian Ocean Lab (AusOcean)

  It is free software: you can redistribute it and/or modify them
  under the terms of the GNU General Public License as published by the
  Free Software Foundation, either version 3 of the License, or (at your
  option) any later version.

  It is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  for more details.

  You should have received a copy of the GNU General Public License
  along with revid in gpl.txt.  If not, see http://www.gnu.org/licenses.

	Derived from librtmp under the GNU Lesser General Public License 2.1
	Copyright (C) 2005-2008 Team XBMC http://www.xbmc.org
	Copyright (C) 2008-2009 Andrej Stepanchuk
	Copyright (C) 2009-2010 Howard Chu
*/
package rtmp

import (
	"errors"
)

// session provides parameters required for an rtmp communication session.
type Session struct {
	rtmp    *C_RTMP
	url     string
	timeout uint
}

// NewSession returns a new session.
func NewSession(url string, connectTimeout uint) *Session {
	return &Session{
		url:     url,
		timeout: connectTimeout,
	}
}

// Open establishes an rtmp connection with the url passed into the
// constructor
func (s *Session) Open() error {
	if s.rtmp != nil {
		return errors.New("rtmp: attempt to start already running session")
	}
	var err error
	s.rtmp, err = startSession(s.rtmp, s.url, s.timeout)
	if s.rtmp == nil {
		return err
	}
	return nil
}

// Close terminates the rtmp connection
func (s *Session) Close() error {
	if s.rtmp == nil {
		return Err(3)
	}
	ret := endSession(s.rtmp)
	s.rtmp = nil
	if ret != 0 {
		return Err(ret)
	}
	return nil
}

// Write writes a frame (flv tag) to the rtmp connection
func (s *Session) Write(data []byte) (int, error) {
	if s.rtmp == nil {
		return 0, Err(3)
	}

	if C_RTMP_IsConnected(s.rtmp) == 0 {
		//if C.RTMP_IsConnected(s.rtmp) == 0 {
		return 0, Err(1)
	}

	if C_RTMP_Write(s.rtmp, data) == 0 {
		//if C.RTMP_Write(s.rtmp, (*byte)(unsafe.Pointer(&data[0])), int32(len(data))) == 0 {
		return 0, Err(2)
	}
	return len(data), nil
}