<?php

namespace MGModule\DNSManager2\mgLibs\custom\dns;

use MGModule\DNSManager2\mgLibs\custom\SubmoduleCap;
use MGModule\DNSManager2\mgLibs\custom\TaskManager;
use MGModule\DNSManager2\models\custom\zone\Repository;

class Strategy
{
    const PRE   = 'pre';
    const AFTER = 'after';

    protected static $events = [
        'addRecord'     => [
            self::AFTER => 'RecordSynchronization:syncAdd'
        ],
        'deleteRecord'  => [
            self::AFTER => 'RecordSynchronization:syncDelete'
        ],
        'editRecord'    => [
            self::AFTER => 'RecordSynchronization:syncEdit'
        ],
        'activateZone'  => [
            self::AFTER => 'RecordSynchronization:syncActivateZone'
        ],
        'terminateZone' => [
            self::AFTER => 'RecordSynchronization:syncTerminateZone'
        ],
        'getRDNSRecord' => [
            self::AFTER => 'RecordSynchronization:syncGetRDNSRecord'
        ],
        'removeRDNS'    => [
            self::AFTER => 'RecordSynchronization:syncRemoveRDNS'
        ],
        'updateRDNS'    => [
            self::AFTER => 'RecordSynchronization:syncUpdateRDNS'
        ],
    ];

    protected $module;

    public function __construct($module)
    {
        $this->module = new SubmoduleCap($module);
    }

    public function __call($name, $args)
    {
        $result = count($args) == 1 ? $this->module->{$name}($args[0]) : $this->module->{$name}($args);
        if (isset(self::$events[$name][self::AFTER]))
        {
            $this->addTask($name, $args, self::AFTER);
        }
        return $result;
    }

    public function __get($name)
    {
        return $this->module->{$name};
    }

    public function getModule()
    {
        return $this->module;
    }

    private function addTask($name, $args, $when)
    {
        $packageServerRepo = new \MGModule\DNSManager2\models\custom\package\server\Repository();
        if ($packageServerRepo->byServerID($this->module->getServer()->id)->get()[0]->isMaster())
        {
            TaskManager::addTask(self::$events[$name][$when], ['submodule' => $this, 'values' => $args, 'zone' => $this->getZone()]);
        }
    }

    private function getZone()
    {
        $zoneRepository = Repository::factory();
        return $zoneRepository->byServerID($this->getServer()->id)->byName($this->getDomain())->get()[0];
    }

}