<?php

namespace OfficeBrain\Bundle\SubShopBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SubshopInstanceMetaRepository.
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SubshopInstanceMetaRepository extends EntityRepository
{
    protected $projectSetting;
    protected $instanceId;
    protected $instanceType;
    protected $cultureId;
    protected $cultureCode;

    public function setProjectSetting($projetSetting)
    {
        $this->projectSetting = $projetSetting;
        $this->prepareProjectSettingData();
    }

    public function getProjectSetting()
    {
        return $this->projetSetting;
    }

    public function prepareProjectSettingData()
    {
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->instanceType = $this->projectSetting['instance_type'];
        $this->userId = $this->projectSetting['user_id'];
        $this->cultureId = $this->projectSetting['culture_id'];
        $this->cultureCode = $this->projectSetting['culture_code'];
    }

    public function findByInstanceId($instanceId = 0)
    {
        if ($instanceId == 0) {
            $instanceId = $this->instanceId;
        }

        return $this->createQueryBuilder('sim')
                    ->select('sim')
                    ->where('sim.instanceId = :instanceId')
                    ->setParameter(':instanceId', $instanceId)
                    ->getQuery()
                    ->getResult();
    }

    public function findByMetaKey($key, $instanceId = 0)
    {
        if ($instanceId == 0) {
            $instanceId = $this->instanceId;
        }

        return $this->createQueryBuilder('sim')
                    ->select('sim')
                    ->where('sim.metaKey = :metaKey AND sim.instanceId = :instanceId')
                    ->setParameter(':metaKey', $key)
                    ->setParameter(':instanceId', $instanceId)
                    ->getQuery()
                    ->getOneOrNullResult();
    }

    public function add($key, $value, $instanceId = 0)
    {
        if ($instanceId == 0) {
            $instanceId = $this->instanceId;
        }

        $subshopInstanceMeta = new SubshopInstanceMeta();
        $subshopInstanceMeta->setInstanceId($instanceId);
        $subshopInstanceMeta->setMetaKey($key);
        $subshopInstanceMeta->setMetaValue($value);

        return $this->commit($subshopInstanceMeta);
    }

    public function set($subshopInstanceMeta)
    {
        return $this->commit($subshopInstanceMeta);
    }

    private function commit($subshopInstanceMeta)
    {
        $this->_em->persist($subshopInstanceMeta);
        $this->_em->flush();

        return $subshopInstanceMeta;
    }
}
