/*
 * See the README file for copyright information and how to reach the author.
 *
 */

#include "common.h"

#define TUNE_TIMEOUT_MS 150

cRMScanner::cRMScanner(cRMDevice* _parent,
        cRMScanChannelListener* _listener)
{
    parent=_parent;
    listener=_listener;

    Start();
}

cRMScanner::~cRMScanner()
{
    Cancel(5);

    parent=NULL;
    listener=NULL;
}

void cRMScanner::FineTune(cRMChannel* _channel) 
{
    parent->Tune(_channel->StartFrequency());
    cCondWait::SleepMs(TUNE_TIMEOUT_MS);
    int startFrequency=_channel->StartFrequency();
    for(int frequency=startFrequency+500;
            Running() && frequency>startFrequency-2500;
            frequency-=50)
    {
        parent->Tune(frequency);
        cCondWait::SleepMs(TUNE_TIMEOUT_MS);
        if(parent->CurrentValue(eSetupSignalPresent)) {
            _channel->AddFrequency(frequency);
        } else {
            parent->Tune(_channel->EndFrequency());
            cCondWait::SleepMs(TUNE_TIMEOUT_MS);
            break;
        }
    }
    int endFrequency=_channel->EndFrequency();
    for(int frequency=endFrequency-500;
            Running() && frequency<endFrequency+2500;
            frequency+=50)
    {
        parent->Tune(frequency);
        cCondWait::SleepMs(TUNE_TIMEOUT_MS);
        if(parent->CurrentValue(eSetupSignalPresent)) {
            _channel->AddFrequency(frequency);
        } else {
            break;
        }
    }
}

void cRMScanner::Action()
{
    cPvrUsb2Plugin::LogDebug("Start scanner");
    int currentFrequency=parent->Frequency();

    int startFrequency=parent->MinValue(eSetupFrequency);
    int endFrequency=parent->MaxValue(eSetupFrequency);

    cRMChannel* current=NULL;

    for(int frequency=startFrequency;
            frequency<=endFrequency && Running(); frequency+=500)
    {
        parent->Tune(frequency);
        cCondWait::SleepMs(TUNE_TIMEOUT_MS);
        if(parent->CurrentValue(eSetupSignalPresent)) {
            cPvrUsb2Plugin::LogDebug("Found signal at: %d", frequency);
            
            if(current && current->IsChannel(frequency)) {
                current->AddFrequency(frequency);
            } else {
                if(current) {
                    FineTune(current);
                }
                current=new cRMChannel(frequency);
                channels.Add(current); 
            }
                            
            if(listener) {
                listener->NewChannel(&channels);
            }
        }
    }
    if(current) {
        FineTune(current);
    }
    if(listener) {
        listener->ScanFinished();
    }

    parent->CloseVideoDevice();
    parent->Tune(currentFrequency);

    cPvrUsb2Plugin::LogDebug("Stopped reader:");
}

