#include "patterninput.h"
#include <QGridLayout>
#include <QLabel>
#include <cmath>

PatternInput::PatternInput(QWidget *parent) : QWidget(parent)
{
    QGridLayout* grid = new QGridLayout(this);
    grid->setSpacing(0);
    for( uint32_t i = 0; i < 56; ++i )
    {
        spadoffButtons.push_back(new QPushButton(this));
        spadoffButtons.back()->setCheckable(true);
        grid->addWidget(spadoffButtons.back(),0,i);
        rechargeButtons.push_back(new QPushButton(this));
        rechargeButtons.back()->setCheckable(true);
        grid->addWidget(rechargeButtons.back(),1,i);
        gateButtons.push_back(new QPushButton(this));
        gateButtons.back()->setCheckable(true);
        grid->addWidget(gateButtons.back(),2,i);
    }
    setLayout(grid);
    setSegments(0);
}

PatternInput::~PatternInput()
{

}

int PatternInput::heightForWidth(int w) const
{
    return (w+2)/3;
}

void PatternInput::getPattern(uint64_t &spadoff, uint64_t &recharge, uint64_t &gate, bool truncate)
{
    getRotatedPattern(spadoff, recharge, gate, 0, truncate);
}

void PatternInput::getRotatedPattern(uint64_t &spadoff, uint64_t &recharge, uint64_t &gate, uint32_t amount, bool truncate)
{
    uint32_t end = truncate ? segments*4 : 56;
    spadoff = 0;
    recharge = 0;
    gate = 0;
    uint64_t mask = 1;
    for( uint32_t i = 0; i < end; ++i ) {
        if( spadoffButtons[(i+amount)%end]->isChecked() ) {
            spadoff |= mask;
        }
        if( rechargeButtons[(i+amount)%end]->isChecked() ) {
            recharge |= mask;
        }
        if( gateButtons[(i+amount)%end]->isChecked() ) {
            gate |= mask;
        }
        mask <<= 1;
    }
}

void PatternInput::setSpadoff(uint64_t p)
{
    for( uint32_t i = 0; i < 56; ++i ) {
        spadoffButtons[i]->setChecked((p&1)==1);
        p >>= 1;
    }
}

void PatternInput::setRecharge(uint64_t p)
{
    for( uint32_t i = 0; i < 56; ++i ) {
        rechargeButtons[i]->setChecked((p&1)==1);
        p >>= 1;
    }
}

void PatternInput::setGate(uint64_t p)
{
    for( uint32_t i = 0; i < 56; ++i ) {
        gateButtons[i]->setChecked((p&1)==1);
        p >>= 1;
    }
}

void PatternInput::setSegments(int count)
{
    segments = std::min(count,56/4);
    for( int32_t i = 0; i < segments*4; ++i ) {
        spadoffButtons[i]->setEnabled(true);
        rechargeButtons[i]->setEnabled(true);
        gateButtons[i]->setEnabled(true);
    }
    for( int32_t i = segments*4; i < 56; ++i ) {
        spadoffButtons[i]->setEnabled(false);
        rechargeButtons[i]->setEnabled(false);
        gateButtons[i]->setEnabled(false);
    }
}


