<?php

/*
 * @author     M2E Pro Developers Team
 * @copyright  M2E LTD
 * @license    Commercial use is forbidden
 */

class Ess_M2ePro_Model_Resource_ActiveRecord_Relation extends Mage_Core_Model_Resource_Db_Abstract
{


    /** @var Ess_M2ePro_Model_ActiveRecord_Relation */
    protected $_relationModel;

    //########################################

    public function __construct($arguments = null)
    {
        if (empty($arguments[0]) || !($arguments[0] instanceof Ess_M2ePro_Model_ActiveRecord_Relation)) {
            throw new Ess_M2ePro_Model_Exception_Logic('Require Ess_M2ePro_Model_Relation model.');
        }

        $this->_relationModel = $arguments[0];
        parent::__construct();
    }

    public function _construct()
    {
        $this->_setResource('M2ePro');
        $this->_idFieldName = 'id';
    }

    //########################################

    public function getMainTable()
    {
        return $this->_relationModel->getParentObject()->getResource()->getMainTable();
    }

    public function getSecondTable()
    {
        return $this->_relationModel->getChildObject()->getResource()->getMainTable();
    }

    //########################################

    protected function _getLoadSelect($field, $value, $object)
    {
        /** @var Ess_M2ePro_Model_ActiveRecord_Relation $object */

        $parentTable = $object->getParentObject()->getResource()->getMainTable();
        $childTable = $object->getChildObject()->getResource()->getMainTable();

        $primaryKey = $object->getParentObject()->getResource()->getIdFieldName();
        $foreignKey = $object->getRelationKey();

        $field  = $this->_getReadAdapter()->quoteIdentifier(sprintf('%s.%s', $parentTable, $field));
        return $this->_getReadAdapter()
                    ->select()
                    ->from($parentTable)
                    ->join($childTable, "`{$childTable}`.`{$foreignKey}` = `{$parentTable}`.`{$primaryKey}`")
                    ->where($field . '= ?', $value);
    }

    protected function _afterLoad(Mage_Core_Model_Abstract $object)
    {
        /** @var Ess_M2ePro_Model_ActiveRecord_Relation $object */

        $object->getParentObject()->getResource()->unserializeFields($object->getParentObject());
        $object->getChildObject()->getResource()->unserializeFields($object->getChildObject());
    }

    public function save(Mage_Core_Model_Abstract $object)
    {
        /** @var Ess_M2ePro_Model_ActiveRecord_Relation $object */
        if ($object->isDeleted()) {
            return $this->delete($object);
        }

        $this->_beforeSave($object);
        if ($object->getParentObject()->hasDataChanges()) {
            $object->getParentObject()->save();
        }

        if ($object->getChildObject()->hasDataChanges()) {
            if (null === $object->getParentObject()->getId()) {
                throw new Ess_M2ePro_Model_Exception_Logic('Parent model doesn\'t exists.');
            }

            $object->getChildObject()
                   ->setData($object->getRelationKey(), $object->getParentObject()->getId())
                   ->save();
        }

        $this->_afterSave($object);
        return $this;
    }

    public function delete(Mage_Core_Model_Abstract $object)
    {
        /** @var Ess_M2ePro_Model_ActiveRecord_Relation $object */
        $this->_beforeDelete($object);

        $object->getParentObject()->delete();
        $object->getChildObject()->delete();

        $this->_afterDelete($object);

        return $this;
    }

    //########################################

    /**
     * @param Mage_Core_Model_Abstract $model
     * @param $key
     * @return bool
     */
    public function isModelContainField(Mage_Core_Model_Abstract $model, $key)
    {
        $helper = Mage::helper('M2ePro/Data_Cache_Runtime');
        $ddlData = $helper->getValue(__METHOD__ . get_class($model));
        if (null === $ddlData) {
            $ddlData = $this->_getWriteAdapter()->describeTable(
                $model->getResource()->getMainTable()
            );
            $helper->setValue(__METHOD__, $ddlData);
        }

        foreach (array_keys($ddlData) as $field) {
            if (strtolower($field) === strtolower($key)) {
                return true;
            }
        }

        return false;
    }

    //########################################
}
