<?php
// Call JobApplicationEventTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "JobApplicationEventTest::main");
}

require_once "PHPUnit/Framework/TestCase.php";
require_once "PHPUnit/Framework/TestSuite.php";

require_once "testConf.php";
require_once ROOT_PATH."/lib/confs/Conf.php";
require_once ROOT_PATH."/lib/confs/sysConf.php";
require_once ROOT_PATH."/lib/models/recruitment/JobApplication.php";
require_once ROOT_PATH."/lib/models/recruitment/JobVacancy.php";
require_once ROOT_PATH."/lib/common/UniqueIDGenerator.php";
require_once ROOT_PATH."/lib/common/LocaleUtil.php";

require_once 'JobApplicationEvent.php';

/**
 * Test class for JobApplicationEvent.
 * Generated by PHPUnit_Util_Skeleton on 2008-03-03 at 22:58:56.
 */
class JobApplicationEventTest extends PHPUnit_Framework_TestCase {
    /**
     * Runs the test methods of this class.
     *
     * @access public
     * @static
     */
    public static function main() {
        require_once "PHPUnit/TextUI/TestRunner.php";

        $suite  = new PHPUnit_Framework_TestSuite("JobApplicationEventTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @access protected
     */
    protected function setUp() {
        $conf = new Conf();
        $this->connection = mysql_connect($conf->dbhost.":".$conf->dbport, $conf->dbuser, $conf->dbpass);
        mysql_select_db($conf->dbname);
        $this->_deleteTables();

        // Insert job titles
        $this->_runQuery("INSERT INTO hs_hr_job_title(jobtit_code, jobtit_name, jobtit_desc, jobtit_comm, sal_grd_code) " .
                "VALUES('JOB001', 'Manager', 'Manager job title', 'no comments', null)");
        $this->_runQuery("INSERT INTO hs_hr_job_title(jobtit_code, jobtit_name, jobtit_desc, jobtit_comm, sal_grd_code) " .
                "VALUES('JOB002', 'Driver', 'Driver job title', 'no comments', null)");
        $this->_runQuery("INSERT INTO hs_hr_job_title(jobtit_code, jobtit_name, jobtit_desc, jobtit_comm, sal_grd_code) " .
                "VALUES('JOB003', 'Typist', 'Typist job title', 'no comments', null)");
        $this->_runQuery("INSERT INTO hs_hr_job_title(jobtit_code, jobtit_name, jobtit_desc, jobtit_comm, sal_grd_code) " .
                "VALUES('JOB004', 'Programmer', 'Software Programmer', 'no comments', null)");

        // Insert employees (managers)
        $this->_runQuery("INSERT INTO hs_hr_employee(emp_number, employee_id, emp_lastname, emp_firstname, emp_middle_name, job_title_code) " .
                    "VALUES(11, '0011', 'Rajasinghe', 'Saman', 'Marlon', 'JOB001')");
        $this->_runQuery("INSERT INTO hs_hr_employee(emp_number, employee_id, emp_lastname, emp_firstname, emp_middle_name, job_title_code, emp_work_email) " .
                    "VALUES(12, '0022', 'Jayasinghe', 'Aruna', 'Shantha', 'JOB001', 'aruna@example.com')");
        $this->_runQuery("INSERT INTO hs_hr_employee(emp_number, employee_id, emp_lastname, emp_firstname, emp_middle_name, job_title_code) " .
                    "VALUES(13, '0042', 'Jayaweera', 'Nimal', 'T', 'JOB001')");
        $this->_runQuery("INSERT INTO hs_hr_employee(emp_number, employee_id, emp_lastname, emp_firstname, emp_middle_name, job_title_code) " .
                    "VALUES(14, '0044', 'Karunarathne', 'Jaya', 'S', 'JOB001')");
        $this->_runQuery("INSERT INTO hs_hr_employee(emp_number, employee_id, emp_lastname, emp_firstname, emp_middle_name, job_title_code) " .
                    "VALUES(15, '0054', 'Ranasinghe', 'Kamal', 'Z', 'JOB001')");

        // Insert to hs_hr_users table
        $this->_runQuery("INSERT INTO `hs_hr_users`(id, user_name, emp_number) VALUES ('USR111','demo', 11)");
        $this->_runQuery("INSERT INTO `hs_hr_users`(id, user_name, emp_number) VALUES ('USR112','kamalr', 12)");
        $this->_runQuery("INSERT INTO `hs_hr_users`(id, user_name) VALUES ('USR113','adminhr')");

        // Insert Job Vacancies
        $this->_runQuery("INSERT INTO hs_hr_job_vacancy(vacancy_id, jobtit_code, manager_id, active, description) " .
                         "VALUES(1, 'JOB001', 11, " . JobVacancy::STATUS_ACTIVE . ", 'Job vacancy 1')");
        $this->_runQuery("INSERT INTO hs_hr_job_vacancy(vacancy_id, jobtit_code, manager_id, active, description) " .
                         "VALUES(2, 'JOB002', 11, " . JobVacancy::STATUS_INACTIVE . ", 'Job vacancy 2')");
        $this->_runQuery("INSERT INTO hs_hr_job_vacancy(vacancy_id, jobtit_code, manager_id, active, description) " .
                         "VALUES(3, 'JOB003', 12, " . JobVacancy::STATUS_INACTIVE . ", 'Job vacancy 3')");

        // Insert Job Applications
        $application = $this->_getJobApplication(1, 1, 'Janaka', 'T', 'Kulathunga', '111 Main Street', 'Apt X2',
                'Colombo', 'Western', '2222', 'Sri Lanka', '01121111121', '077282828282', 'janaka@example.com',
                'aaa bbb', JobApplication::STATUS_SECOND_INTERVIEW_SCHEDULED);
        $application->setHiringManagerName('Saman Rajasinghe');
        $application->setJobTitleName('Manager');
        $this->jobApplications[1] = $application;

        $application = $this->_getJobApplication(2, 2, 'Kamal', 'S', 'Manawarathne', '222 Sea Street', 'Suite B2',
                'Kandy', 'Central', '111111', 'England', '33211121', '079982828282', 'kamal@etst.com',
                'asdfasdf', JobApplication::STATUS_FIRST_INTERVIEW_SCHEDULED);
        $application->setHiringManagerName('Saman Rajasinghe');
        $application->setJobTitleName('Driver');
        $this->jobApplications[2] = $application;

        $application = $this->_getJobApplication(3, 3, 'Ruwan', 'S', 'Nawarathne', '393 Hill Street', '#2',
                'Nuwaraeliya', 'Central', '2333', 'Sri Lanka', '05121111121', '072282828282', 'rywab@sfmple.com',
                'aaa sdf bbb', JobApplication::STATUS_SUBMITTED);
        $application->setHiringManagerName('Aruna Jayasinghe');
        $application->setJobTitleName('Typist');
        $this->jobApplications[3] = $application;

        $this->_createJobApplications($this->jobApplications);

        // Create job application events
        $createdTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("-1 hours"));
        $eventTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("+5 days"));

        // Events for first job application
        $this->_createEvent(1, 1, $createdTime, 'USR111', 13, $eventTime,
            JobApplicationEvent::EVENT_SCHEDULE_FIRST_INTERVIEW, JobApplicationEvent::STATUS_INTERVIEW_FINISHED,
            "1st Interview notes, here");

        $createdTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("-0.6 hours"));
        $eventTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("+6 days"));
        $this->_createEvent(2, 1, $createdTime, 'USR112', 14, $eventTime,
            JobApplicationEvent::EVENT_SCHEDULE_SECOND_INTERVIEW, JobApplicationEvent::STATUS_INTERVIEW_SCHEDULED,
            "2nd Interview notes, here");

        // Events for second job application
        $createdTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("-0.3 hours"));
        $eventTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("+7 days"));

        $this->_createEvent(3, 2, $createdTime, 'USR113', 14, $eventTime,
            JobApplicationEvent::EVENT_SCHEDULE_FIRST_INTERVIEW, JobApplicationEvent::STATUS_INTERVIEW_SCHEDULED,
            "3rd Interview notes, here");

        UniqueIDGenerator::getInstance()->resetIDs();
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @access protected
     */
    protected function tearDown() {
        $this->_deleteTables();
        UniqueIDGenerator::getInstance()->resetIDs();
    }

    private function _deleteTables() {
        $this->_runQuery("DELETE FROM `hs_hr_users` WHERE id in ('USR111', 'USR112', 'USR113')");
        $this->_runQuery("TRUNCATE TABLE `hs_hr_job_application_events`");
        $this->_runQuery("TRUNCATE TABLE `hs_hr_job_application`");
        $this->_runQuery("TRUNCATE TABLE `hs_hr_job_vacancy`");
        $this->_runQuery("TRUNCATE TABLE `hs_hr_job_title`");
        $this->_runQuery("TRUNCATE TABLE `hs_hr_employee`");
    }

    /**
     * @todo Implement testGetCreatorName().
     */
    public function testGetCreatorName() {

        // Creator with corresponding employee who doesnt have email
        $jobApplication = JobApplicationEvent::getJobApplicationEvent(1);
        $this->assertEquals('Saman Rajasinghe', $jobApplication->getCreatorName());

        // Creator without corresponding user.
        $jobApplication = JobApplicationEvent::getJobApplicationEvent(3);
        $this->assertEquals('adminhr', $jobApplication->getCreatorName());
    }

    /**
     * @todo Implement testGetCreatorEmail().
     */
    public function testGetCreatorEmail() {

        // Creator with corresponding employee who doesnt have email
        $jobApplication = JobApplicationEvent::getJobApplicationEvent(1);
        $this->assertEquals('', $jobApplication->getCreatorEmail());

        // Creator with corresponding employee who has email
        $jobApplication = JobApplicationEvent::getJobApplicationEvent(2);
        $this->assertEquals('aruna@example.com', $jobApplication->getCreatorEmail());

        // Creator without corresponding user.
        $jobApplication = JobApplicationEvent::getJobApplicationEvent(3);
        $this->assertEquals('', $jobApplication->getCreatorEmail());
    }

    /**
     * Test save() method
     */
    public function testSave() {

        // New event
        $before = $this->_getNumRows();
        $createdTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("-1 hours"));
        $eventTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("+5 days"));

        $event = $this->_getEvent(null, 1, $createdTime, 'USR111', 11,
            $eventTime, JobApplicationEvent::EVENT_SCHEDULE_SECOND_INTERVIEW,
            JobApplicationEvent::STATUS_INTERVIEW_FINISHED, 'Notes aa');
        $id = $event->save();

        $after = $this->_getNumRows();
        $this->assertEquals(1, $after - $before);
        $this->_checkExistsInDb($event);


        // Update
        $before = $this->_getNumRows();

        $event = JobApplicationEvent::getJobApplicationEvent(1);
        $event->setNotes('New Notes');
        $event->setStatus(JobApplicationEvent::STATUS_INTERVIEW_FINISHED);
        $event->setEventType(JobApplicationEvent::EVENT_SCHEDULE_SECOND_INTERVIEW);
        $event->save();

        $after = $this->_getNumRows();
        $this->assertEquals($before, $after);
        $this->_checkExistsInDb($event);

        // invalid id
        $before = $this->_getNumRows();
        $event->setId('A1k');
        try {
            $event->save();
        } catch (JobApplicationEventException $e) {
            $this->assertEquals(JobApplicationEventException::INVALID_PARAMETER, $e->getCode());
        }

        $after = $this->_getNumRows();
        $this->assertEquals($before, $after);
    }

    /**
     * Test getEvents() method
     */
    public function testGetEvents() {

        $event1 = JobApplicationEvent::getJobApplicationEvent(1);
        $event2 = JobApplicationEvent::getJobApplicationEvent(2);
        $event3 = JobApplicationEvent::getJobApplicationEvent(3);

        // Invalid app id
        try {
            $events = JobApplicationEvent::getEvents('12A');
        } catch (JobApplicationEventException $e) {
            $this->assertEquals(JobApplicationEventException::INVALID_PARAMETER, $e->getCode());
        }

        // app id with no events
        $events = JobApplicationEvent::getEvents(3);
        $this->assertTrue(is_array($events));
        $this->assertEquals(0, count($events));

        // app id with events
        $events = JobApplicationEvent::getEvents(1);
        $this->assertTrue(is_array($events));
        $this->assertEquals(2, count($events));
        $expected = array($event1, $event2);

        $this->_compareEventsWithOrder($expected, $events);

        $events = JobApplicationEvent::getEvents(2);
        $expected = array($event3);
        $this->assertTrue(is_array($events));
        $this->assertEquals(1, count($events));
        $this->_compareEventsWithOrder($expected, $events);

    }

    /**
     * Test case for getJobApplicationEvent().
     */
    public function testGetJobApplicationEvent() {

        $createdTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("-1 hours"));
        $eventTime = date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT, strtotime("+5 days"));

        // invalid id
        try {
            $event = JobApplicationEvent::getJobApplicationEvent('12A');
            $this->fail("Exception expected");
        } catch (JobApplicationEventException $e) {
            $this->assertEquals(JobApplicationEventException::INVALID_PARAMETER, $e->getCode());
        }

        // valid id but not available
        $event = JobApplicationEvent::getJobApplicationEvent(121);
        $this->assertNull($event);

        // valid available id
        $event = JobApplicationEvent::getJobApplicationEvent(1);
        $this->assertNotNull($event);
        $this->assertEquals(1, $event->getApplicationId());
        $this->assertEquals('USR111', $event->getCreatedBy());
        $this->assertEquals(13, $event->getOwner());
        $this->assertEquals(JobApplicationEvent::EVENT_SCHEDULE_FIRST_INTERVIEW, $event->getEventType());
        $this->assertEquals(JobApplicationEvent::STATUS_INTERVIEW_FINISHED, $event->getStatus());
        $this->assertEquals("1st Interview notes, here", $event->getNotes());

    }

    /**
     * Create a JobApplication object with the passed parameters
     */
    private function _getJobApplication($id, $vacancyId, $firstName, $middleName, $lastName, $street1, $street2,
            $city, $province, $zip, $country, $mobile, $phone, $email, $qualifications, $status = JobApplication::STATUS_SUBMITTED) {
        $application = new JobApplication($id);
        $application->setVacancyId($vacancyId);
        $application->setFirstName($firstName);
        $application->setMiddleName($middleName);
        $application->setLastName($lastName);
        $application->setStreet1($street1);
        $application->setStreet2($street2);
        $application->setCity($city);
        $application->setProvince($province);
        $application->setZip($zip);
        $application->setCountry($country);
        $application->setMobile($mobile);
        $application->setPhone($phone);
        $application->setEmail($email);
        $application->setQualifications($qualifications);
        $application->setStatus($status);
        $application->setAppliedDateTime(date(LocaleUtil::STANDARD_TIMESTAMP_FORMAT));
        return $application;
    }

    /**
     * Saves the given JobApplication objects in the database
     *
     * @param array $applications Array of JobApplication objects to save.
     */
    private function _createJobApplications($applications) {
        foreach ($applications as $application) {

            $sql = sprintf("INSERT INTO hs_hr_job_application(application_id, vacancy_id, firstname, middlename, ".
                        "lastname, street1, street2, city, country_code, province, zip, " .
                        "phone, mobile, email, qualifications, status, applied_datetime) " .
                        "VALUES(%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s')",
                        $application->getId(), $application->getVacancyId(), $application->getFirstName(),
                        $application->getMiddleName(), $application->getLastName(), $application->getStreet1(),
                        $application->getStreet2(), $application->getCity(), $application->getCountry(),
                        $application->getProvince(), $application->getZip(), $application->getPhone(),
                        $application->getMobile(), $application->getEmail(),
                        $application->getQualifications(), $application->getStatus(),
                        $application->getAppliedDateTime());
            $this->assertTrue(mysql_query($sql), mysql_error());
        }
        UniqueIDGenerator::getInstance()->initTable();
    }

    /**
     * Create job application event with the passed parameters
     *
     * @param int $id
     * @param int $applicationId
     * @param String $createdTime
     * @param String $createdBy
     * @param int $ownerId
     * @param String $eventTime
     * @param int $eventType
     * @param int $eventStatus
     * @param String $notes
     */
    private function _createEvent($id, $applicationId, $createdTime, $createdBy, $ownerId, $eventTime,
        $eventType, $eventStatus, $notes) {

        $sql = sprintf("INSERT INTO `hs_hr_job_application_events`(`id`,`application_id`,`created_time`," .
                        "`created_by`, `owner`, `event_time`, `event_type`, `status`, `notes`) " .
                        "VALUES (%d, %d, '%s', '%s', %d, '%s', %d, %d, '%s')",
                        $id, $applicationId, $createdTime, $createdBy, $ownerId, $eventTime,
                        $eventType, $eventStatus, $notes);
        $this->assertTrue(mysql_query($sql), mysql_error());
        UniqueIDGenerator::getInstance()->initTable();
    }

    /**
     * Check's that the passed appliation event exists in the database
     *
     * @param JobApplicationEvent Job Application Event to check
     */
    private function _checkExistsInDb($application) {

        $id = $application->getId();
        $appId = $application->getApplicationId();
        $createdBy = $application->getCreatedBy();
        $owner = $application->getOwner();
        $eventType = $application->getEventType();
        $status = $application->getStatus();
        $status = is_null($status) ? 'null' : $status;
        $notes = $application->getNotes();
        $notes = is_null($notes) ? 'null' : "'{$notes}'";

        $where = "id = {$id} AND application_id = {$appId} AND created_by = '{$createdBy}' AND owner = {$owner}" .
                " AND notes = {$notes} AND status = {$status}";

        $this->assertEquals(1, $this->_getNumRows($where));
    }

    /**
     * Returns the number of rows in the hs_hr_job_application_events table
     *
     * @param  string $where where clause
     * @return int number of rows
     */
    private function _getNumRows($where = null) {

        $sql = "SELECT COUNT(*) FROM hs_hr_job_application_events";
        if (!empty($where)) {
            $sql .= " WHERE " . $where;
        }

        $result = mysql_query($sql);
        $row = mysql_fetch_array($result, MYSQL_NUM);
        $count = $row[0];
        return $count;
    }

    /**
     * Get Job Application Event with the passed parameters
     *
     * @param int $id Job Application Event Id
     * @param int $appId Job Application Event Id
     * @param string $createdTime
     * @param string $createdBy
     * @param int $owner
     * @param string $eventTime
     * @param int $eventType
     * @param int $status
     * @param string $notes
     */
    private function _getEvent($id, $appId, $createdTime, $createdBy, $owner,
            $eventTime, $eventType, $status, $notes) {

        $event = new JobApplicationEvent();
        $event->setId($id);
        $event->setApplicationId($appId);
        $event->setCreatedTime($createdTime);
        $event->setCreatedBy($createdBy);
        $event->setOwner($owner);
        $event->setEventTime($eventTime);
        $event->setEventType($eventType);
        $event->setStatus($status);
        $event->setNotes($notes);

        return $event;
    }

    /**
     * Compares two array of JobApplicationEvent objects verifing they contain the same
     * objects and considering the order
     *
     * @param array $expected Expected
     * @param array $result Result
     */
    private function _compareEventsWithOrder($expected, $result) {
        $this->assertEquals(count($expected), count($result));
        $i = 0;
        foreach ($expected as $application) {
            $this->assertEquals($application, $result[$i]);
            $i++;
        }

    }
    /**
     * Run given sql query, checking the return value
     */
    private function _runQuery($sql) {
        $this->assertTrue(mysql_query($sql), mysql_error());
    }

}

// Call JobApplicationEventTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "JobApplicationEventTest::main") {
    JobApplicationEventTest::main();
}
?>

